Skip
Arish's avatar

32. Docker Security Fundamentals


Non-Root User

dockerfile
1# Create user
2RUN addgroup --system app && adduser --system --group app
3
4# Set ownership
5RUN chown -R app:app /app
6
7# Switch to non-root
8USER app
9
10CMD ["rails", "server"]

Read-Only Filesystem

yaml
1services:
2  web:
3    read_only: true
4    tmpfs:
5      - /tmp
6      - /app/tmp

Security Scanning

bash
1# Scan image for vulnerabilities
2docker scout quickview myapp:latest
3docker scout cves myapp:latest
4
5# Using Trivy
6trivy image myapp:latest

Secrets Management

yaml
1# Docker secrets (Swarm)
2services:
3  web:
4    secrets:
5      - db_password
6
7secrets:
8  db_password:
9    file: ./secrets/db_password.txt

Best Practices

  1. Use minimal base images (alpine, slim)
  2. Don't run as root
  3. Scan images regularly
  4. Keep images updated
  5. Use multi-stage builds
  6. Don't store secrets in images