DEV Community

Yash Sonawane
Yash Sonawane

Posted on

Docker Series: Episode 20 β€” Docker Security Best Practices & Secrets Management πŸ”’

Welcome back! In previous episodes, we covered Docker Compose, Networking, Swarm, and Volumes. Now it’s time to focus on security β€” protecting your containers, images, and sensitive information.


πŸ”Ή Why Docker Security Matters

  • Containers are isolated, but misconfigurations can expose vulnerabilities.
  • Running containers as root, storing secrets in plain text, or using untrusted images can compromise your system.
  • Security best practices ensure your apps remain safe in production.

πŸ”Ή Secure Images

  • Always use official or trusted base images.
  • Keep images small to reduce attack surface.
  • Regularly update images.
  • Scan images with tools like Trivy, Clair, or Docker scan.

Example:

docker scan my_app
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Running Containers Safely

  • Avoid running containers as root. Use a non-root user in your Dockerfile:
RUN addgroup appgroup && adduser -S appuser -G appgroup
USER appuser
Enter fullscreen mode Exit fullscreen mode
  • Use resource limits (--memory, --cpus) to avoid resource abuse.
  • Avoid --privileged mode unless absolutely necessary.

πŸ”Ή Managing Secrets

  • Never hardcode passwords or API keys in Dockerfiles.
  • Use Docker Secrets (in Swarm) or external secret managers:

    • Docker Secrets
    • AWS Secrets Manager
    • HashiCorp Vault

Example (Swarm secret):

docker secret create db_password ./db_password.txt
docker service create --name db --secret db_password postgres:latest
Enter fullscreen mode Exit fullscreen mode
  • In Compose (v3.4+), you can define secrets:
secrets:
  db_password:
    file: ./db_password.txt

services:
  db:
    image: postgres:latest
    secrets:
      - db_password
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Network Security

  • Use custom networks to isolate services.
  • Only expose necessary ports.
  • Consider using firewalls or reverse proxies for additional layers of security.

πŸ”Ή Best Practices Summary

  1. Use trusted base images.
  2. Regularly scan images.
  3. Run as non-root user.
  4. Limit resources.
  5. Manage secrets securely.
  6. Isolate networks and containers.

πŸ”Ή Hands-On Challenge

  1. Scan your app image using Trivy.
  2. Run the container as a non-root user.
  3. Create a secret and attach it to your container.
  4. Test network isolation using custom networks.

βœ… Next Episode: Episode 21 β€” Docker Logging & Monitoring Essentials β€” learn to keep track of container health and logs in production.

Top comments (0)