Module 7 Lesson 1: Docker Security Best Practices
Fortify your containers. Explore the 'Top 10' security practices for hardening Docker images and runtimes against modern threats.
Module 7 Lesson 1: Docker Security Best Practices
Containers are often thought of as "Secure by default" because of isolation. However, a misconfigured container can be a direct doorway into your host server. This module focuses on the Security-First mindset for Docker.
1. The Strategy: Defense in Depth
Security isn't one "Switch" you flip. It's a series of layers:
- Image Layer: Hardening the
Dockerfile. - Runtime Layer: Hardening the
docker runflags. - Host Layer: Securing the server running Docker.
2. Top 5 Image Security Rules
- Use Trusted Base Images: Only pull from "Official" repositories (like
python,node,nginx). Avoid images likesuper-hacker-66/python-readywhich might contain malware. - Fixed Versions: Never use
:latest. Use a specific version (e.g.,3.11-alpine) to prevent "Poisoned" updates from creeping in. - Minimal Installation: If you don't need
curl,git, orsshinside your container, don't install them. They are just tools for an attacker to use once they break in. - No Secrets in Dockerfiles: Never put passwords, API keys, or certificates in
ENVorLABELinstructions. (Anyone can see them withdocker inspect). - Multi-Stage Builds: (Review Module 6). Use this to ensure your source code and build tools are NOT in the final image.
3. Top 5 Runtime Security Rules
- Read-Only File Systems: If your app only needs to serve files and doesn't need to write to them, use
--read-only. - Limit Resources: (Review Module 4). Use
--memoryand--cpusto prevent Denial of Service (DoS) attacks. - Disable Privileged Mode: NEVER use
--privilegedunless you are building a tool that must control the hardware (e.g., Docker-in-Docker). - No Root: We will dive deep into this in the next lesson.
- Network Isolation: Use private bridge networks to group related containers and isolate them from the rest of the host.
4. The "Audit" Command: docker scan
Docker provides a built-in vulnerability scanner.
docker scan my-image:latest
It will check every layer of your image against a database of known security holes (CVEs) and tell you which packages need to be updated.
Exercise: The Security Scan
- Pull an image you frequently use (e.g.,
node:latest). - Run
docker scan <image-name>(or use an external tool likeSnykorTrivy). - Look at the list of "Vulnerabilities." How many are labeled "Critical"?
- Now, pull the
node:alpineversion of that same image and scan it. - Comparison: Which image is safer? Why does the "size" of the image correlate with the "number of security holes"?
Summary
Security in Docker is about Shrinking the Surface Area. Every package you remove, every permission you take away, and every secret you hide makes your application significantly harder to exploit.
Next Lesson: The #1 security rule: Running as non-root.