Secure Your Docker Container
2 min readOct 30, 2024
Here’s a quick, practical checklist for hardening Docker containers with commands and examples.
1. Implement TLS Encryption
it’s essential to employ HTTPS and TLS to ensure confidentiality, integrity, and authentication.
- Run Docker in TLS Mode (Server):
dockerd --tlsverify --tlscacert=myca.pem --tlscert=myserver-cert.pem --tlskey=myserver-key.pem -H=0.0.0.0:237
- Authenticate Docker with TLS (Client):
docker --tlsverify --tlscacert=myca.pem --tlscert=client-cert.pem --tlskey=client-key.pem -H=SERVERIP:2376 info
2. Use Minimal Base Or Distroless Images
- Start with Small Images (e.g.,
alpine
).
FROM alpine:latest
- Or with distroless images from chainguard
FROM cgr.dev/chainguard/php:latest
3. Run as Non-Root User
- Add a User in Dockerfile and run the application as that user.
docker run -u 4000 alpine
- Or
FROM alpine
RUN groupadd -r myuser && useradd -r -g myuser myuser
# <HERE DO WHAT YOU HAVE TO DO AS A ROOT USER LIKE INSTALLING PACKAGES ETC.>
USER myuser
4. Enable Seccomp Profile
- Apply Seccomp Profile to restrict system calls.
docker run --security-opt seccomp=/path/to/profile.json <image>
5. Apply AppArmor Profile
- Use AppArmor for OS-Level Restrictions.
docker run --security-opt apparmor=/path/to/profile.json <image>
6. Set Read-Only Filesystem
- Restrict Write Access for Immutable Containers.
docker run --read-only <image>
7. Restrict Capabilities
- Drop Unnecessary Privileges using
--cap-drop
.
docker run --cap-drop=ALL --cap-add=NET_BIND_SERVICE <image>
8. Disable Privileged Mode
- Avoid Privileged Containers to prevent host access.
docker run --privileged=false <image>
9. Limit Networking Capabilities
- Use Minimal Network Mode (e.g., none or host) if needed.
docker run --network=none <image>
10. Set Up Logging and Monitoring
- Enable Logging Driver for monitoring container activity.
docker run --log-driver=syslog <image>
11. Use Environment Variables Securely
- Avoid Hardcoding Secrets; Use Docker Secrets.
docker secret create my_secret /path/to/secret_file
docker service create --secret my_secret <image>
12. Scan Images for Vulnerabilities
- Use Image Scanners like Trivy or Clair.
trivy image <image>
grype <image> --scope all-layers
docker scout cves <image>
13. Keep Docker and Images Updated
- Regularly Update Docker and Rebuild Images.
14. Implement Health Checks
- Add health checks in your Dockerfile to monitor the application’s state and ensure it runs as expected.
HEALTHCHECK --interval=30s --timeout=10s CMD curl --fail http://localhost:8080 || exit 1
15. Limit Docker API Access
- Restrict Access to Docker Daemon to avoid unauthorized access.
sudo systemctl disable docker.socket