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
πΉ 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
- 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
- In Compose (v3.4+), you can define secrets:
secrets:
db_password:
file: ./db_password.txt
services:
db:
image: postgres:latest
secrets:
- db_password
πΉ 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
- Use trusted base images.
- Regularly scan images.
- Run as non-root user.
- Limit resources.
- Manage secrets securely.
- Isolate networks and containers.
πΉ Hands-On Challenge
- Scan your app image using Trivy.
- Run the container as a non-root user.
- Create a secret and attach it to your container.
- 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)