Skillversitas

Docker Security Best Practices

Docker security best practices for production.

1. Use a Non-Root User

# Create a non-root user
RUN addgroup -g 1001 -S nodejs && \
    adduser -S nodejs -u 1001

# Set the working directory
WORKDIR /app

# Copy files with the correct permissions
COPY --chown=nodejs:nodejs . .

# Run as non-root
USER nodejs

2. Scan Images

# Use Docker Scout
docker scout cves myapp:latest

# Use Trivy
trivy image myapp:latest

3. Use Secrets

# Docker Compose with secrets
services:
  api:
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt

4. Resource Limits

services:
  api:
    deploy:
      resources:
        limits:
          cpus: '1.0'
          memory: 512M

5. Network Security

# Use an internal network
docker network create --internal secure-net

# Don't expose unneeded ports
# Wrong:
docker run -d -p 3306:3306 mysql
# Right:
docker run -d -p 127.0.0.1:3306:3306 mysql

Use Case: Application Security

version: '3.8'

services:
  database:
    image: postgres:15
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - db-data:/var/lib/postgresql/data
    networks:
      - backend
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G

  api:
    build: ./backend
    user: "1000:1000"
    read_only: true
    tmpfs:
      - /tmp
    security_opt:
      - no-new-privileges:true
    cap_drop:
      - ALL
    cap_add:
      - NET_BIND_SERVICE
    networks:
      - backend

networks:
  backend:
    internal: true

secrets:
  db_password:
    file: ./secrets/db_password.txt

6. Docker Bench Security

# Run Docker Bench
docker run --rm --net host --pid host --userns host --cap-add audit_control \
  -v /var/lib:/var/lib:ro \
  -v /var/run/docker.sock:/var/run/docker.sock:ro \
  docker/docker-bench-security

Everyday Use Case

Case: An admin needs to secure Docker.

# Scan the image
docker scout cves myapp:latest

# Run Docker Bench
docker run --rm --net host --pid host docker/docker-bench-security

# Check running containers
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

Best Practices Checklist

  • [ ] Use a non-root user
  • [ ] Scan images for vulnerabilities
  • [ ] Use Docker secrets
  • [ ] Set resource limits
  • [ ] Use internal networks
  • [ ] Read-only filesystem
  • [ ] Disable privilege escalation
  • [ ] Update the base image regularly
  • [ ] Monitor container activity
  • [ ] Back up data regularly

Conclusion

Docker security should be a priority. Apply best practices to protect your application from threats.