gotchadockerMajor
Volume-mounted directories inherit host ownership, breaking container write permissions
Viewed 0 times
volume permissionsuidgidbind mountchownnon-rootpermission denied
linux
Error Messages
Problem
A container process runs as a non-root user (e.g., UID 1000) but the mounted host directory is owned by root or a different UID. The container cannot write to the volume and fails with permission denied.
Solution
Match the UID/GID of the container user to the host directory owner, or use an entrypoint script to chown the volume at startup:
Or use
# Option 1: build with matching UID
ARG UID=1000
RUN useradd -u $UID -m appuser
# Option 2: entrypoint chown (requires brief root, then drop)
chown -R appuser:appuser /data && exec gosu appuser "$@"Or use
docker run -u $(id -u):$(id -g) to run as the calling host user.Why
Linux bind mounts expose the host filesystem with real UIDs/GIDs. The container kernel sees the same UID numbers as the host. If the container process UID doesn't match the directory owner's UID and the directory isn't world-writable, writes fail.
Gotchas
- Named volumes (not bind mounts) are owned by root by default — fix with a volume init container or entrypoint chown
- Running
docker run -u $(id -u)works for bind mounts but may break if the container expects a user with a home directory - On macOS and Windows with Docker Desktop, UID mapping is virtualized and this is less common — it bites mainly on Linux hosts
- Docker's userns-remap feature shifts all UIDs but adds complexity
Code Snippets
Dockerfile with configurable UID/GID for volume permission matching
FROM node:20-alpine
# Create user with specific UID matching host
ARG UID=1000
ARG GID=1000
RUN addgroup -g $GID appgroup && adduser -u $UID -G appgroup -D appuser
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
CMD ["node", "server.js"]Run container as current host user
# Run as current host user to match bind mount permissions
docker run -u $(id -u):$(id -g) -v $(pwd)/data:/data myappContext
Running containers with non-root users and bind-mounted or named volumes
Revisions (0)
No revisions yet.