How to umount a usb drive from my app running in a docker container

I am able to mount and share the contents of the drive with my docker container, but I cannot unmount the drive from my app because of permission issues. I’ve been trying several options for a couple of days unsuccessfully; I feel that I am missing something fundamental. Is there a simple method to unmount a usb drive from my app running on a docker container?

Thanks in advance.

Hi, I’m the Toradex AI Assistant.

I might make mistakes or occasionally get you wrong. Our support team will step in if needed.


I’d be glad to help with unmounting USB drives from your containerized application! To provide the most accurate guidance, could you let me know which hardware and OS version you’re using?

For example:

  • Hardware: Verdin i.MX8M Plus, Verdin AM62, Apalis i.MX8QP, Colibri i.MX8X, etc.
  • OS and version: Torizon OS 6.8.2, Torizon OS 7.2.0, BSP 7, etc.

You can get this information by running the tdx-info command on your device. More details about this command are available at https://developer.toradex.com/software/development-resources/tdx-info/.

The unmounting approach will depend on your specific platform configuration, container setup, and the permissions model you’re using. Once I know your setup, I can provide the exact steps and configuration needed for your environment.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.

@ToradexAI

$ sudo tdx-info
Password:

Software summary

Bootloader: U-Boot

Kernel version: 6.6.119-7.5.0-ge5c5595adb06 #1-Torizon SMP PREEMPT Mon Jan 5 09:23:13 UTC 2026
Kernel command line: root=LABEL=otaroot rootfstype=ext4 quiet logo.nologo vt.global_cursor_default=0 plymouth.ignore-serial-consoles splash fbcon=map:3 ostree=/ostree/boot.1/torizon/71ff576e829a77dcfa9003f0be4c1a56a55370751330f346fd8812482c2e59e9/0 pd_ignore_unused
Distro name: NAME=“Torizon OS”
Distro version: VERSION_ID=7.5.0-build.30
Distro variant: VARIANT=“Docker”
Hostname: colibri-imx8x-06996015

Hardware info

HW model: Toradex Colibri iMX8QXP on Colibri Evaluation Board V3

Toradex version: 0038 V1.0D
Serial number: 06996015
Processor arch: aarch64

torizon@colibri-imx8x-06996015:/usr/bin$

Perfect! Now I can help you with unmounting USB drives from your containerized application on your Colibri iMX8QXP running Torizon OS 7.5.0.

Understanding the Permission Issue

The permission issue you’re experiencing is fundamental to container security (1). Containers run in an isolated environment and don’t have direct access to mount/unmount operations by default (2).

Solutions for Unmounting USB Drives

Option 1: Use Privileged Mode (Development Only)

For development purposes, you can run your container in privileged mode, which gives it full access to the host system (1):

docker run --privileged -v /dev:/dev your-container

Warning: This approach removes the security isolation of containers and should be avoided in production (1).

Option 2: Grant Specific Capabilities

A more secure approach is to add specific capabilities needed for mount operations (1):

docker run --cap-add SYS_ADMIN -v /dev:/dev your-container

Option 3: Use Device and Volume Mounts

You can expose the necessary devices and mount points (2):

docker run -v /dev:/dev -v /media:/media --device-cgroup-rule='c 8:* rmw' your-container

This gives access to block devices (major number 8) with read, write, and mknod permissions (2).

Option 4: Host-based Unmounting

Consider implementing the unmount operation on the host system and communicating with your container through:

  • Shared volumes
  • Network APIs
  • File-based signaling

Docker Compose Configuration

If you’re using Docker Compose, you can configure the necessary permissions (2):

services:
  your-app:
    image: your-image
    privileged: false
    cap_add:
      - SYS_ADMIN
    volumes:
      - /dev:/dev
      - /media:/media
    device_cgroup_rules:
      - "c 8:* rmw"  # Block devices

Best Practices

  1. Avoid privileged mode in production environments (1)
  2. Use specific capabilities rather than broad permissions (1)
  3. Consider running as the torizon user inside the container for hardware access (1)
  4. Implement proper error handling for mount/unmount operations

The key is balancing functionality with security - use the minimal permissions necessary for your specific use case.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.

@ToradexAI

Using your suggested Docker Compose Configuration does not solve the problem. I am still getting the “must be superuser to unmount” message when try to run the “umount” command.

You’re correct that the Docker Compose configuration alone isn’t sufficient for unmounting operations. The “must be superuser to unmount” error indicates that even with SYS_ADMIN capability, the unmount operation requires root privileges.

Alternative Approaches for Unmounting

Option 1: Use D-Bus for System Operations

Similar to how system operations like reboot can be performed without root permissions, you can use D-Bus to communicate with system services for unmounting (1). Here’s how it works:

# docker run -it --rm -v /var/run/dbus:/var/run/dbus torizon/debian:4
# apt update && apt-get install -y dbus
# dbus-send --system --print-reply --dest=org.freedesktop.login1 /org/freedesktop/login1 "org.freedesktop.login1.Manager.Reboot" boolean:true

(1)

You can adapt this approach for unmounting by using UDisks2 D-Bus interface instead of the login manager.

Option 2: Bind Mount with Proper Propagation

Based on community experience with USB device management (2), you need to configure bind mount propagation correctly:

services:
  your-app:
    image: your-image
    volumes:
      - type: bind
        source: /media
        target: /media
        bind:
          propagation: shared

(2)

Option 3: Run Container as Root User

While not ideal for production, you can run the container as root to bypass permission restrictions:

services:
  your-app:
    image: your-image
    user: root
    cap_add:
      - SYS_ADMIN
    volumes:
      - /dev:/dev
      - /media:/media

Option 4: Host-Side Script Approach

Create a host-side script that your container can trigger through file system signals or network communication. This keeps the privileged operations on the host while maintaining container security.

Key Considerations

The fundamental issue is that unmounting requires root privileges, which containers typically don’t have for security reasons (3). The SYS_ADMIN capability provides some administrative functions but doesn’t elevate the user to root level for all operations.

For production systems, I recommend implementing the unmount functionality on the host side and having your container communicate the unmount request through a secure channel rather than giving the container root privileges.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.

@ToradexAI

Please provide further details on option 4

Detailed Host-Side Script Approach

The host-side script approach separates privileged operations from the container application, maintaining security while providing the needed functionality.

Implementation Overview

This approach uses bind-mount volumes to share communication files between the container and host (1). The container writes unmount requests to a shared location, and a host-side service monitors for these requests and executes the privileged unmount operations.

Step 1: Create Shared Communication Directory

On the host, create a directory for communication:

# mkdir -p /home/torizon/usb-manager
# chown torizon:torizon /home/torizon/usb-manager

Step 2: Host-Side Monitoring Script

Create a script on the host that monitors for unmount requests:

#!/bin/bash
# /home/torizon/usb-manager/monitor-unmount.sh

WATCH_DIR="/home/torizon/usb-manager"
REQUEST_FILE="$WATCH_DIR/unmount-request"
RESPONSE_FILE="$WATCH_DIR/unmount-response"

while true; do
    if [ -f "$REQUEST_FILE" ]; then
        # Read the device to unmount
        DEVICE=$(cat "$REQUEST_FILE")
        
        # Perform the unmount operation
        if sudo umount "$DEVICE" 2>/dev/null; then
            echo "SUCCESS: $DEVICE unmounted" > "$RESPONSE_FILE"
        else
            echo "ERROR: Failed to unmount $DEVICE" > "$RESPONSE_FILE"
        fi
        
        # Remove the request file
        rm "$REQUEST_FILE"
    fi
    sleep 1
done

Step 3: Docker Compose Configuration

Configure your container to access the shared directory using bind-mount (1):

services:
  your-app:
    image: your-image
    volumes:
      - "/home/torizon/usb-manager:/usb-manager"
      - "/media:/media:ro"  # Read-only access to mount points
    user: "1000:1000"  # Run as torizon user

(1)

Step 4: Container Application Code

In your container application, implement the unmount request:

import time
import os

def request_unmount(device_path):
    request_file = "/usb-manager/unmount-request"
    response_file = "/usb-manager/unmount-response"
    
    # Write unmount request
    with open(request_file, 'w') as f:
        f.write(device_path)
    
    # Wait for response
    timeout = 10  # seconds
    start_time = time.time()
    
    while time.time() - start_time < timeout:
        if os.path.exists(response_file):
            with open(response_file, 'r') as f:
                response = f.read().strip()
            os.remove(response_file)
            return response
        time.sleep(0.1)
    
    return "ERROR: Timeout waiting for unmount response"

# Usage example
result = request_unmount("/media/usb-drive")
print(result)

Step 5: Systemd Service for Monitoring

Create a systemd service to run the monitoring script automatically:

# /etc/systemd/system/usb-unmount-monitor.service
[Unit]
Description=USB Unmount Monitor Service
After=network.target

[Service]
Type=simple
User=torizon
ExecStart=/home/torizon/usb-manager/monitor-unmount.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable and start the service:

# sudo systemctl enable usb-unmount-monitor.service
# sudo systemctl start usb-unmount-monitor.service

Advantages of This Approach

  1. Security: Container runs with minimal privileges (2)
  2. Separation of Concerns: Privileged operations isolated to host
  3. Flexibility: Can extend to handle multiple USB management operations
  4. Monitoring: Easy to log and audit unmount operations

Alternative Communication Methods

Instead of file-based communication, you could also use:

  • Named pipes (FIFOs): More efficient for real-time communication
  • Unix domain sockets: Better for bidirectional communication
  • Network sockets: If container and host need network-based communication

The file-based approach is simpler to implement and debug, making it ideal for USB unmount operations where real-time performance isn’t critical.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.

@ToradexAI

The permissions problem is now moved to “sudo umount “$DEVICE” 2>/dev/null”. Is there a way to overcome this?

You’re absolutely right - the permission issue persists on the host side. Here are several approaches to overcome this:

Option 1: Configure Sudoers for Passwordless Unmount

Add the torizon user to sudoers with specific permissions for unmount operations:

# Add to /etc/sudoers.d/usb-unmount
torizon ALL=(ALL) NOPASSWD: /bin/umount

Then modify your script to use:

sudo umount "$DEVICE" 2>/dev/null

Option 2: Use UDisks2 for User-Space Unmounting

UDisks2 allows non-root users to unmount removable devices. Install and use it:

# Install udisks2 if not present
sudo apt update && sudo apt install udisks2

# In your monitoring script, replace sudo umount with:
udisksctl unmount -b "$DEVICE" 2>/dev/null

Option 3: Leverage udev Rules for Automatic Management

Based on community experience with USB automounting (1), you can create custom udev rules that handle both mounting and unmounting. Create a udev rule that triggers scripts with appropriate permissions:

# /etc/udev/rules.d/99-usb-mount.rules
ACTION=="remove", SUBSYSTEM=="block", KERNEL=="sd[a-z][0-9]", RUN+="/usr/local/bin/usb-unmount.sh %k"

Option 4: Use systemd-mount for User Operations

Systemd provides user-space mounting capabilities:

# Instead of umount, use:
systemctl --user stop media-usb\\x2ddrive.mount 2>/dev/null

Option 5: Modify Script to Use User Groups

Ensure the torizon user is in appropriate groups for device access (2). The torizon user should already be mapped to several groups including those needed for hardware device access (2).

Recommended Approach: UDisks2

For your use case, I recommend Option 2 (UDisks2) as it’s designed specifically for user-space device management and doesn’t require modifying system security policies.

Modified monitoring script:

#!/bin/bash
# /home/torizon/usb-manager/monitor-unmount.sh

WATCH_DIR="/home/torizon/usb-manager"
REQUEST_FILE="$WATCH_DIR/unmount-request"
RESPONSE_FILE="$WATCH_DIR/unmount-response"

while true; do
    if [ -f "$REQUEST_FILE" ]; then
        DEVICE=$(cat "$REQUEST_FILE")
        
        # Use udisksctl instead of sudo umount
        if udisksctl unmount -b "$DEVICE" 2>/dev/null; then
            echo "SUCCESS: $DEVICE unmounted" > "$RESPONSE_FILE"
        else
            echo "ERROR: Failed to unmount $DEVICE" > "$RESPONSE_FILE"
        fi
        
        rm "$REQUEST_FILE"
    fi
    sleep 1
done

This approach maintains security while providing the functionality you need without requiring sudo privileges.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.

Greetings @vic,

Just to make sure I understand your use-case. From what I understand so far, you want to run the umount command from within a Docker container, but without needing root/sudo permissions?

This might be hard/tricky since umount is a command that normally requires elevated permissions in the first place.

I am able to mount and share the contents of the drive with my docker container

Do you perform the mounting of the drive from outside of the container environment first? Or do you mount from within the container environment?

Best Regards,
Jeremias

Hi @jeremias.tx ,

Well, it is the other way round: I want to umount a usb drive from my app running on a docker container (that belongs to a non-root user) and, for that purpose, the container/app needs root permissions. Thus, the problem may be rephrased as “how to provide root permissions to my app that is running on a container belonging to a no-root user, so it can umount a usb drive”. Surely we would be on the safe side if able to provide root permission *only* for umounting drives on, e.g., “/media/” folder.

The container is allowed to access the usb drive contents by appropriate binding at the docker-compose file.

Thanks in advance

V

@ToradexAI , your suggested approach is working. Thanks for your input.

Would it also work if I save monitor-unmount.sh script in /etc folder so its content is captured when running torizoncore-builder isolate command?

V

Excellent! I’m glad the approach is working for you.

Saving Scripts in /etc for TorizonCore Builder Isolation

Yes, you can save the monitor-unmount.sh script in the /etc directory, and it will be captured when running the torizoncore-builder isolate command (1). The isolate command captures configuration changes from the /etc directory, including modifications, additions, deletions, and file permissions (1).

Implementation Approach

Place your script in an appropriate subdirectory under /etc, such as:

/etc/usb-manager/monitor-unmount.sh

The isolate command will capture this along with the proper file permissions and ownership (1). Files and directories permissions and ownership are saved in the /etc/.tcattr metadata file together with all other isolated files (1).

Key Considerations

  1. File Permissions: Ensure the script has executable permissions before running isolate:

    chmod +x /etc/usb-manager/monitor-unmount.sh
    
  2. Systemd Service: If you create a systemd service file, place it in /etc/systemd/system/ so it’s also captured by the isolate command (1).

  3. Excluded Files: The isolate command ignores certain system files, but your custom scripts won’t be affected by these exclusions (1).

Workflow Integration

When you use this approach with TorizonCore Builder (2):

  1. Configure your device with the script in /etc
  2. Run torizoncore-builder isolate to capture the changes (1)
  3. Use torizoncore-builder union to apply the changes to your custom image (1)
  4. Deploy the custom image with your USB management functionality built-in

This approach ensures your USB unmount functionality becomes part of your custom Torizon OS image and will be available on all devices that receive this image.

Best regards, Toradex AI Assistant.


Did you like my answer? :+1: :-1:

If I answered your question, please tick the “Solution” checkbox.

For follow-up questions to me, please use @ToradexAI in your post.