Lesson 2: The Security Guard (Docker Security)
A container with root access, a writable filesystem, and unpatched vulnerabilities is a hacker's dream. Security isn't an afterthought — it's built into every layer of your Docker workflow.
Rule 1: Never Run as Root
By default, containers run as root. This is dangerous — if an attacker breaks into your app, they have root access inside the container.
# ✅ Create and use a non-root user
FROM node:18-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
WORKDIR /app
COPY --chown=appuser:appgroup . .
USER appuser
CMD ["node", "server.js"]
Rule 2: Use Read-Only Filesystems
Prevent attackers from writing malicious files:
docker run --read-only --tmpfs /tmp nginx
--read-only— The container filesystem is read-only.--tmpfs /tmp— Allow writes only to/tmp(in memory).
Rule 3: Limit Resources
Prevent containers from consuming all host resources:
docker run -d \
--memory="256m" \
--cpus="0.5" \
--pids-limit 100 \
my-app
--memory— Maximum RAM.--cpus— Maximum CPU cores.--pids-limit— Prevent fork bombs.
Rule 4: Drop Capabilities
Linux capabilities give containers specific kernel permissions. Drop everything you don't need:
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE nginx
Rule 5: Scan for Vulnerabilities
Every image contains OS packages that may have known vulnerabilities:
# Docker Scout (built-in)
docker scout quickview nginx
docker scout cves nginx
# Trivy (popular open-source scanner)
trivy image nginx:latest
Rule 6: Use Trusted Base Images
- ✅ Use official images from Docker Hub.
- ✅ Use verified publisher images.
- ❌ Avoid random images with few downloads/stars.
- ✅ Pin to specific versions, not
latest.
Rule 7: Don't Store Secrets in Images
# ❌ NEVER DO THIS
ENV API_KEY=sk-1234567890
# ✅ Use runtime environment variables
docker run -e API_KEY=$API_KEY my-app
# ✅ Or use Docker secrets (Swarm/Compose)
Security Checklist
✅ Non-root user (USER instruction)
✅ Read-only filesystem
✅ Resource limits (memory, CPU, PIDs)
✅ Minimal capabilities (--cap-drop ALL)
✅ No secrets in Dockerfile
✅ Vulnerability scanning in CI/CD
✅ Official/verified base images
✅ Specific version tags
✅ .dockerignore excludes sensitive files
✅ Multi-stage builds (no build tools in prod)
Mission Objective
Harden your containers:
- Check the user: Run
docker run --rm alpine whoamito see the default user. - Lock the filesystem: Run
docker run --rm --read-only alpine touch /test— it should fail! - Scan for vulnerabilities: Run
docker scout quickview nginx.
🎉 Congratulations!
You've completed the Docker & Containers course! You can now build images, manage containers, compose multi-service applications, and deploy them securely.
Next Steps:
- Containerize your own projects — start with a simple web app.
- Set up a CI/CD pipeline that builds and pushes Docker images.
- Learn Kubernetes — orchestrating containers at scale!