Bind Mount Permissions

Difficulty: Advanced

Question

How do you handle 'Permission Denied' errors when using bind mounts between Linux hosts and containers?

Answer

This is a common issue because Docker doesn't automatically map UIDs (User IDs) between host and container. If a file on the host is owned by UID 1000 and the container user is UID 0 (root), it works. But if your container user is 1001, it will fail.

**Solutions**: 1. **Matching UID**: Ensure the container user has the same UID as the host user. 2. **Entrypoint Script**: Use a script that changes the ownership of mounted volumes at runtime (requires root to start). 3. **User Namespaces**: Enable user namespace remapping in the Docker daemon (most secure). 4. **Lazy Fix**: Change host file permissions to 777 (dangerous/not recommended).

Code examples

Passing UID/GID at runtime

# Pass the current user's UID and GID to the container
docker run -u $(id -u):$(id -g) -v $(pwd):/app node:alpine npm install

This tells Docker to run the process as the exact same user that owns the files on the host, preventing all permission issues.

Key points

Concepts covered

UID/GID, User mapping, Permission denied