Introduction
Permission denied errors when mounting volumes in Docker are common when the container user doesn't match the host filesystem permissions. This guide explains the root causes and multiple resolution strategies.
Symptoms
- 'Permission denied' when writing to mounted volumes
- Read-only filesystem errors
- Application cannot create log files or temp directories
- File ownership showing as 'nobody' or '100999'
Common Causes
- Container runs as root but files need specific ownership
- Host UID/GID doesn't exist inside container
- Named volumes initialized with wrong permissions
- SELinux/AppArmor security contexts blocking access
- Read-only root filesystem with no writable volumes
Step-by-Step Fix
- 1.Check current volume permissions:
- 2.```bash
- 3.docker exec <container> ls -la /app/data
- 4.ls -la /host/path
- 5.
` - 6.Run container with matching user ID:
- 7.```bash
- 8.# Get host user ID
- 9.id -u
- 10.id -g
# Run with matching IDs docker run -u $(id -u):$(id -g) -v $(pwd):/app myimage ```
- 1.Use named volumes with proper initialization:
- 2.```dockerfile
- 3.FROM node:18
- 4.RUN mkdir -p /app/data && chown -R node:node /app
- 5.USER node
- 6.VOLUME ["/app/data"]
- 7.
` - 8.Fix SELinux contexts (if applicable):
- 9.```bash
- 10.docker run -v /host:/container:Z myimage
- 11.# Or :z for shared context
- 12.
` - 13.Use entrypoint scripts to fix permissions at runtime:
- 14.```bash
- 15.#!/bin/sh
- 16.if [ "$FIX_PERMISSIONS" = "true" ]; then
- 17.chown -R appuser:appgroup /app/data
- 18.fi
- 19.exec "$@"
- 20.
`