Skillversitas

Docker Bind Mounts

Bind mounts allow you to mount directories or files from the host into a container.

Syntax

# Mount a directory
docker run -d -v /host/path:/container/path myapp

# Mount read-only
docker run -d -v /host/path:/container/path:ro myapp

# Mount a file
docker run -d -v /host/config.json:/app/config.json myapp

# Mount with an owner
docker run -d -v /host/path:/container/path:rw,Z myapp

Use Case: Development

# Run with hot reload
docker run -d \
  --name dev-app \
  -v $(pwd):/app \
  -v /app/node_modules \
  -p 3000:3000 \
  node:18-alpine \
  npm run dev

Use Case: Configuration

# Mount an nginx config
docker run -d \
  --name web \
  -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
  -p 80:80 \
  nginx

# Mount multiple configs
docker run -d \
  --name app \
  -v $(pwd)/config:/app/config:ro \
  -v $(pwd)/logs:/app/logs \
  myapp

Use Case: Application

version: '3.8'

services:
  api:
    build: ./backend
    volumes:
      - ./backend/src:/app/src
      - ./backend/config:/app/config:ro
      - api-uploads:/app/uploads
    environment:
      - NODE_ENV=development

  nginx:
    image: nginx:alpine
    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/ssl:/etc/nginx/ssl:ro
    ports:
      - "80:80"
      - "443:443"

volumes:
  api-uploads:

Everyday Use Case

Case: A developer needs to edit code directly.

# Run with a bind mount
docker run -d \
  --name dev \
  -v $(pwd):/app \
  -w /app \
  node:18-alpine \
  npm run dev

# Edit code on the host, and it appears in the container immediately

Permission Issues

# Linux: make sure the UID/GID is correct
docker run -d \
  --user $(id -u):$(id -g) \
  -v $(pwd):/app \
  myapp

# macOS: use :delegated
docker run -d \
  -v $(pwd):/app:delegated \
  myapp

Best Practices

  1. Use bind mounts for development: For hot reload
  2. Use named volumes for data: For persistence
  3. Mount configs as read-only: For security
  4. Mind permissions: Especially on Linux

Troubleshooting

File not visible

# Check the mount point
docker inspect container_name | grep Mounts

# Check permissions
docker exec container_name ls -la /app

Permission denied

# Check ownership
ls -la /host/path

# Fix permissions
sudo chown -R $(id -u):$(id -g) /host/path

Conclusion

Bind mounts are very useful for development. For production, use named volumes for data persistence.