A comprehensive, hands-on guide to Docker security best practices with real-world examples and lab exercises.
This guide takes you from basic Docker security concepts to advanced hardening techniques through practical, reproducible lab exercises. Each lab builds on previous knowledge while remaining self-contained.
- Security Auditing: Using Docker Bench Security for CIS compliance
- Secure Images: Building hardened, minimal container images
- Least Privilege: Implementing proper access controls
- Image Signing: Verifying container authenticity
- Network Security: Isolating and securing container communications
- AI/ML Security: Protecting machine learning workloads
- Supply Chain Security: SBOM generation and vulnerability scanning
- Network Architecture: Multi-tier segmentation and encryption
This Docker Security guide is part of the OpsCart Labs collection — production-grade hands-on labs built from real Fortune 500 retail & pharmaceutical cluster experience.
Visit OpsCart Labs for:
- 70+ Total Labs across 2 lab series
- ~60 Hours of hands-on content
- GitHub-Backed — All labs available as open source
- Automated Validation — Exam tips, real scenarios, war-room notes
🔐 Docker Security: Practical Guide (This Repository)
- Runtime escape, secrets management, image hardening, and secret management
- 10 labs covering CIS benchmarks to production security patterns
- Status: Active development
☸️ Certified Kubernetes Administrator Exam Prep (production-cka)
- 70 hands-on labs covering every CKA exam domain
- Automated validation scripts, real exam tips, Fortune 500 cluster notes
- Cluster Arch 25% • Networking 20% • Workloads 15% • Storage 10% • Troubleshooting 30%
- Status: 5/70 labs complete
🎯 Kubernetes Practical Exercises (Coming Soon)
- Focused exercises covering core Kubernetes concepts
- Ideal for engineers who want to sharpen specific skills without full exam prep
- Pods & Workloads • Networking • Storage • Debugging
Production-Grade — Built from managing 8+ production AKS clusters
Real Scenarios — Fortune 500 pharmaceutical & retail experience
GitHub-First — All content open source and version controlled
Practitioner Authority — IEEE Senior Member, DZone Core Member, CNCF contributor
Explore all labs: opscart.com/labs
Foundation labs covering essential Docker security concepts.
What You'll Learn:
- Run comprehensive security audits using Docker Bench Security
- Understand CIS Docker Benchmark compliance checks
- Identify common security misconfigurations
- Fix vulnerable container configurations
Key Concepts:
- Privileged container detection
- Network namespace isolation
- Capability management
- Security profile enforcement
Time: 30-45 minutes
What You'll Learn:
- Compare insecure vs secure container configurations
- Understand and apply Linux capabilities
- Implement read-only filesystems
- Use tmpfs for required write operations
- Apply security options like no-new-privileges
Key Concepts:
- Linux capability system
- Read-only root filesystems
- Capability dropping (drop all, add specific)
- tmpfs mounts with noexec and nosuid
- Container hardening without breaking functionality
Time: 45-60 minutes
What You'll Learn:
- Run containers as non-root users
- Drop unnecessary Linux capabilities
- Implement read-only filesystems
- Configure security contexts
Key Concepts:
- User namespace remapping
- Capability dropping
- Resource constraints
- Security policies
Time: 30-45 minutes
What You'll Learn:
- Sign container images with Cosign
- Verify image signatures before deployment
- Implement Docker Content Trust
- Enforce signing policies
- Manage signing keys securely
Key Concepts:
- Digital signatures and cryptographic verification
- Cosign and Sigstore project
- Docker Content Trust (DCT)
- Keyless signing with OIDC
- Supply chain attack prevention
- Policy enforcement for signed images
Time: 45-60 minutes
What You'll Learn:
- Configure secure Docker networks
- Implement network policies
- Use service mesh patterns
- Secure inter-container communication
Key Concepts:
- Custom bridge networks
- Network segmentation
- Encrypted communication
- Traffic control
Time: 30-45 minutes
What You'll Learn:
- Secure containerized machine learning workloads
- Set appropriate resource limits for ML containers
- Implement input validation and rate limiting
- Protect model intellectual property
- Monitor ML container behavior
- Deploy ML models securely in production
Key Concepts:
- Resource management for ML workloads
- Model extraction and adversarial attacks
- API authentication and authorization
- Input validation for ML endpoints
- Model encryption and access control
- Monitoring and anomaly detection for ML services
Time: 60-90 minutes
Advanced labs covering supply chain security and comprehensive network security.
What You'll Learn:
- Generate Software Bill of Materials (SBOM) using Syft
- Scan SBOMs for vulnerabilities with Grype
- Compare SBOM versions to track changes
- Integrate SBOM generation into CI/CD pipelines
- Meet compliance requirements (Executive Order 14028)
Key Concepts:
- SBOM formats (SPDX, CycloneDX, Syft JSON)
- Supply chain transparency
- Vulnerability management
- Dependency tracking
- CVE detection and remediation
- CI/CD security automation
Key Tools:
- Syft: SBOM generation
- Grype: Vulnerability scanning
- Azure DevOps and GitHub Actions: CI/CD integration
Time: 45-60 minutes
Why This Matters:
- Required for US federal software (EO 14028)
- Enables rapid response to vulnerabilities (e.g., Log4Shell)
- Provides complete software inventory
- Supports compliance audits (PCI DSS, SOC 2)
What You'll Learn:
- Implement network isolation between containers
- Design multi-tier segmented architectures
- Use internal networks for complete database isolation
- Configure TLS encryption for container-to-container communication
- Identify and fix 8 common network misconfigurations
5 Interactive Scenarios:
Scenario 1: Network Isolation (3-4 minutes)
- Create isolated networks with DNS resolution
- Implement gateway containers spanning multiple networks
- Understand network boundaries
Scenario 2: Multi-Tier Segmentation (4-5 minutes)
- Design 3-tier architecture (web/app/database)
- Force traffic through monitored gateways
- Prevent direct web-to-database access
Scenario 3: Internal Networks (3-4 minutes)
- Use internal networks with no external gateway
- Achieve complete database isolation
- Meet PCI DSS and HIPAA requirements
Scenario 4: TLS Encryption (4-5 minutes)
- Generate self-signed certificates
- Configure nginx with TLS
- Implement encrypted container communication
- Understand TLS performance implications
Scenario 5: Common Misconfigurations (3-4 minutes)
- Learn 8 common network security mistakes:
- Using default bridge network (no DNS)
- Using
--network host(bypasses security) - Exposing unnecessary ports (databases)
- No resource limits (DoS risk)
- Running as root
- Using
--privilegedmode - Flat network architecture
- No health checks
Key Concepts:
- Defense in depth
- Network segmentation
- Zero-trust architecture
- TLS/mTLS implementation
- Resource management
- Security misconfiguration prevention
Time: 18-22 minutes (all scenarios) or 3-5 minutes each
Why This Matters:
- Prevents lateral movement during breaches
- Meets compliance requirements
- Protects sensitive data in transit
- Enables zero-trust architectures
- Real-world production patterns
Hands-on container escape scenarios — understanding how attackers break out of containers.
What You'll Learn:
- Execute 5 real container escape techniques in a controlled environment
- Understand why blocking docker.sock alone is not sufficient
- Implement runtime detection with Falco and admission control with Kyverno
- Audit containers for dangerous configurations that standard scans miss
5 Escape Scenarios:
Scenario 1: Docker Socket Escape (25 min)
- Mount docker.sock → install Docker CLI → create privileged container → mount host / → chroot to host root
- The most common escape in production (Jenkins, Portainer, DinD, Watchtower)
Scenario 2: Privileged Container Escape (15 min)
- 5 demonstrations: capability comparison, host filesystem via block device, network namespace escape, cgroup release_agent (Felix Wilhelm technique), detection
--privilegeddisables every security boundary simultaneously
Scenario 3: CAP_SYS_ADMIN Abuse (20 min)
- Single capability that enables 30+ system operations including mount and namespace manipulation
- Passes standard security audits (
Privileged: false) while providing near-privileged access
Scenario 4: Host Path Mount Abuse (15 min)
/etcbind mount reads credentials directly; docker.sock escalation chain (two containers cooperating)- Risk-classified audit: CRITICAL (docker.sock), HIGH (/etc), MEDIUM (system paths)
Scenario 5: /proc and /sys Exposure (15 min)
- Reconnaissance: kernel version → CVE targeting, network data → lateral movement, process list → service discovery
- Read-only mounts prevent writes but not information disclosure
Key Concepts:
- Container isolation boundaries and how each is broken
- The audit gap: what scanners check vs what attackers exploit
- Defense-in-depth: Falco rules, Kyverno admission policies, audit scripts
- Docker Desktop vs Linux host behavioral differences
Defense Artifacts Generated:
- Falco runtime detection rules (Scenarios 3, 4, 5)
- Kyverno admission policies (Scenarios 4, 5)
- Audit scripts with risk classification (Scenarios 2, 3, 4, 5)
Time: 2-2.5 hours (all scenarios) or 15-25 minutes each
Why This Matters:
- Blocking docker.sock and --privileged is necessary but not sufficient
- CAP_SYS_ADMIN, host mounts, and /proc are the blind spots attackers use next
- Runtime detection rules generated here are production-ready
Advanced production security patterns for secret management.
What You'll Learn:
- Identify 5 common secret leakage patterns in Docker environments
- Implement Docker Swarm native secrets with encrypted storage
- Integrate HashiCorp Vault for centralized secret management
- Use BuildKit secret mounts for build-time credentials
- Scan repositories for leaked secrets with automated tools
- Prevent secret commits using pre-commit hooks and CI/CD integration
Key Concepts:
- Anti-patterns: hardcoded secrets, ENV vars, build args, git history leaks
- Docker Swarm secrets: encrypted at rest, in-memory tmpfs mounts
- External secret management: Vault dev mode and production patterns
- BuildKit secret mounts: build-time secrets that never persist
- Secret scanning: GitLeaks, pre-commit hooks, CI/CD integration
5 Interactive Scenarios:
Scenario 1: Anti-Patterns (15 min)
- Demonstrate 5 ways secrets leak in Docker containers
- Hardcoded secrets visible in
docker history - Environment variables exposed in
docker inspect - Build arguments persisting in image layers
- Mounted files with wrong permissions (world-readable)
- Git history leaks (permanent even after deletion)
Scenario 2: Docker Swarm Secrets (20 min)
- Create and manage secrets via Swarm CLI
- Deploy services with secret mounts at
/run/secrets/ - Verify secrets NOT visible in
docker inspect(metadata only) - Understand encrypted storage and tmpfs security properties
- Compare with anti-patterns (ENV vars vs Swarm secrets)
Scenario 3: HashiCorp Vault Integration (25 min)
- Run Vault in dev mode (containerized, macOS compatible)
- Store and retrieve secrets via CLI and HTTP API
- Integrate applications with Vault at runtime
- Understand centralized secret management
- Compare Vault vs Swarm secrets (environment flexibility)
Scenario 4: BuildKit Secret Mounts (15 min)
- Pass secrets to builds without ARG leakage
- Access private npm/pip registries during build
- Use SSH keys for private git repos during build
- Implement multi-stage builds with secret isolation
- Verify secrets don't persist in final image or history
Scenario 5: Secret Scanning (15 min)
- Scan repositories for leaked secrets with GitLeaks
- Detect secrets in git history (even after deletion)
- Set up pre-commit hooks to prevent secret commits
- Integrate secret scanning in CI/CD pipelines (GitHub Actions, Azure DevOps)
- Create custom detection rules for company-specific secrets
Time: 90 minutes (all scenarios) or 15-25 minutes each
Why This Matters:
- Secrets in git are permanent (even after deletion)
- Environment variables leak through docker inspect and logs
- BuildKit secrets enable secure builds without image pollution
- Automated scanning prevents accidental commits
- Multi-layered approach (Swarm + Vault + scanning) for production
Tier 2 (Linux VM - Lab 11 Planned):
- Process memory forensics to detect secrets in RAM
- tmpfs verification (prove secrets are in-memory only)
- Production Vault with TLS, audit logging, and dynamic secrets
- Zero-downtime secret rotation with SIGHUP handling
- Compliance audit reports (PCI-DSS, SOC 2)
- Docker Engine 20.10+
- Docker Compose 2.0+
- Linux, macOS, or Windows with WSL2
- Basic Docker knowledge
- Terminal/command line familiarity
- Clone the repository:
git clone https://github.com/opscart/docker-security-practical-guide.git
cd docker-security-practical-guide- Start with Lab 01:
cd labs/01-docker-bench-security
./run-audit.sh- Follow along with the README in each lab directory
- Start with Lab 01 to understand security auditing
- Progress sequentially through Level 1 (Labs 01-06)
- Complete all exercises before moving forward
- Review the "Common Issues" sections
- Move to Level 2 (Labs 07-08) for advanced topics
- Jump to specific labs based on your needs
- Use as a reference for security patterns
- Adapt examples to your use cases
- Focus on Level 2 labs for advanced techniques
- Contribute improvements via pull requests
- Use Lab 01 for baseline security assessments
- Reference CIS Benchmark mappings
- Lab 07 for supply chain compliance
- Lab 08 for network architecture reviews
- Adapt checklists for your compliance needs
- Document findings using provided templates
- Lab 07 for CI/CD security integration
- Lab 08 for production network architecture
- Use automation scripts in your pipelines
- Implement security best practices from all labs
Each lab is self-contained and includes:
README.md: Comprehensive guide with theory and practicedocker-compose.yml: Ready-to-run configurations- Scripts: Automation for common tasks
- Examples: Both vulnerable and secure configurations
- CI/CD configs: Azure DevOps and GitHub Actions (Labs 07-08)
# Navigate to lab directory
cd labs/XX-lab-name
# Review the README
cat README.md
# Run the lab exercise
./run-demo.sh # or specific lab script
# Clean up
./cleanup.shLab 01: Security Auditing (CIS Benchmark)
↓
Lab 02: Secure Configurations (Capabilities, Read-only FS)
↓
Lab 03: Least Privilege (Non-root, Resource Limits)
↓
Lab 04: Image Signing (Cosign, Content Trust)
↓
Lab 05: Network Security Basics (Custom Networks)
↓
Lab 06: AI/ML Security (Model Protection)
Lab 07: Supply Chain Security
(SBOM, Vulnerability Scanning)
↓
Lab 08: Network Security
(5 Scenarios: Isolation to Encryption)
Lab 09: Runtime Escape
(5 Scenarios: Socket to /proc)
Estimated Time:
- Level 1 (Labs 01-06): 4-6 hours
- Level 2 (Labs 07-08): 2-3 hours
- Level 3 (Lab 09): 2-2.5 hours
- Level 4 (Lab 10): 90 minutes
- Complete guide: 9.5-13 hours
- With practice exercises: 14-19 hours
## 🛠️ Tools & Technologies
### Security Tools Used
**Level 1:**
- **Docker Bench Security**: CIS compliance auditing
- **Trivy**: Vulnerability scanning
- **Cosign**: Container signing
- **Anchore**: Image analysis
- **Notary**: Content trust
**Level 2:**
- **Syft**: SBOM generation (Lab 07)
- **Grype**: Vulnerability scanning (Lab 07)
- **OpenSSL**: Certificate generation (Lab 08)
- **nginx**: TLS configuration (Lab 08)
### Technologies Covered
- Docker Engine & Docker Compose
- Linux Security Modules (AppArmor, SELinux)
- Seccomp profiles
- User namespaces
- Capability systems
- Docker networking (bridge, internal, overlay)
- TLS/mTLS encryption
- CI/CD integration (Azure DevOps, GitHub Actions)
## 📝 Best Practices Summary
### Image Security
- Use minimal base images (alpine, distroless)
- Scan for vulnerabilities regularly
- Generate and maintain SBOMs (Lab 07)
- Sign and verify images (Lab 04)
- Use specific tags, never `latest`
- Implement multi-stage builds
### Runtime Security
- Run as non-root user (Lab 03)
- Drop unnecessary capabilities (Lab 02)
- Use read-only filesystems (Lab 02)
- Enable security profiles
- Set resource limits (Lab 08)
- Implement health checks (Lab 08)
### Network Security
- Use custom bridge networks (Lab 08)
- Implement multi-tier segmentation (Lab 08)
- Use internal networks for databases (Lab 08)
- Avoid host network mode (Lab 08)
- Encrypt traffic with TLS (Lab 08)
- Control ingress/egress
### Supply Chain Security (Lab 07)
- Generate SBOMs for all images
- Scan regularly for vulnerabilities
- Track dependency changes
- Automate in CI/CD pipelines
- Meet compliance requirements
- Respond quickly to CVEs
### Secrets Management
- Never hardcode credentials
- Use Docker secrets or external vaults
- Rotate secrets regularly
- Limit secret access scope
- Audit secret usage
### Operational Security
- Regular security audits (Lab 01)
- Keep Docker updated
- Monitor container behavior
- Log security events
- Incident response plan
- Track SBOM and vulnerability changes (Lab 07)
## 🏗️ Architecture Patterns
### Multi-Tier Segmentation (Lab 08)
┌──────────────┐ ┌──────────────┐ ┌─────────────────┐ │ Public Net │ │ App Net │ │ Database Net │ │ │ │ │ │ (INTERNAL) │ │ [Web] │◄─────►│ [App] │◄─────►│ [DB] │ │ :8443 │ TLS │ │ │ No Gateway │ └──────────────┘ └──────────────┘ └─────────────────┘ ▲ │ Internet
### Supply Chain Security (Lab 07)
[Container] → [Syft] → [SBOM] → [Grype] → [Security Report] ↓ [SPDX/CycloneDX/JSON] ↓ [CVE Database] ↓ [Critical/High/Medium/Low]
## 🤝 Contributing
Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Add your improvements
4. Test thoroughly
5. Submit a pull request
### Contribution Ideas
- Additional lab exercises
- Security tool integrations
- Cloud platform examples (AWS, Azure, GCP)
- Kubernetes security labs
- Advanced threat scenarios
- Additional SBOM formats
- More network security patterns
## 📚 Additional Resources
### Official Documentation
- [Docker Security](https://docs.docker.com/engine/security/)
- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker)
- [Docker Bench Security](https://github.com/docker/docker-bench-security)
- [Syft (SBOM Generation)](https://github.com/anchore/syft)
- [Grype (Vulnerability Scanning)](https://github.com/anchore/grype)
### Security Standards
- [NIST Container Security](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-190.pdf)
- [OWASP Docker Top 10](https://owasp.org/www-project-docker-top-10/)
- [CIS Controls](https://www.cisecurity.org/controls)
- [Executive Order 14028](https://www.whitehouse.gov/briefing-room/presidential-actions/2021/05/12/executive-order-on-improving-the-nations-cybersecurity/) - SBOM Requirements
### SBOM Resources (Lab 07)
- [SPDX Specification](https://spdx.dev/)
- [CycloneDX Standard](https://cyclonedx.org/)
- [CISA SBOM Resources](https://www.cisa.gov/sbom)
- [NTIA SBOM Minimum Elements](https://www.ntia.gov/report/2021/minimum-elements-software-bill-materials-sbom)
### Network Security Resources (Lab 08)
- [Docker Network Documentation](https://docs.docker.com/network/)
- [Container Network Security](https://kubernetes.io/docs/concepts/services-networking/network-policies/)
- [TLS Best Practices](https://wiki.mozilla.org/Security/Server_Side_TLS)
### Community Resources
- [Docker Security Subreddit](https://reddit.com/r/docker)
- [Docker Community Slack](https://dockercommunity.slack.com)
- [Stack Overflow Docker Tag](https://stackoverflow.com/questions/tagged/docker)
- [CNCF Slack](https://slack.cncf.io/)
## 🐛 Troubleshooting
### Common Issues
**Issue: Permission denied running scripts**
```bash
chmod +x script-name.sh
Issue: Docker daemon not running
sudo systemctl start dockerIssue: Port already in use
docker ps # Check running containers
docker-compose down # Stop services
lsof -i :PORT # Find process using portIssue: Image pull failures
docker login # Authenticate if needed
docker pull image-name # Manual pull to testIssue: Syft/Grype not found (Lab 07)
# Install Syft
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin
# Install Grype
curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/binIssue: Certificate generation fails (Lab 08)
# Ensure OpenSSL is installed
openssl version
# Check certificate generation script
cd labs/08-network-security/certs
chmod +x generate-certs.sh
./generate-certs.shIssue: Network already exists (Lab 08)
# Clean up all networks
cd labs/08-network-security
./cleanup.shTrack your progress:
- Lab 01: Security Auditing ⏱️ 30-45 min
- Lab 02: Secure Configurations ⏱️ 45-60 min
- Lab 03: Least Privilege ⏱️ 30-45 min
- Lab 04: Image Signing ⏱️ 45-60 min
- Lab 05: Network Security Basics ⏱️ 30-45 min
- Lab 06: AI/ML Security ⏱️ 60-90 min
- Lab 07: Supply Chain Security (SBOM) ⏱️ 45-60 min
- Lab 08: Network Security (5 Scenarios) ⏱️ 18-22 min
- Lab 09: Runtime Escape (5 Scenarios) ⏱️ 2-2.5 hrs
- Lab 10: Secrets Management (5 Scenarios) ⏱️ 90 min
Total Time: 9.5-13 hours
MIT License - see LICENSE file for details
- Docker team for security tools and documentation
- CIS for the Docker Benchmark
- OWASP for security guidelines
- Anchore team for Syft and Grype (Lab 07)
- Sigstore project for Cosign (Lab 04)
- Open source security community
- CNCF for cloud native security standards
- Author: Shamsher Khan
- GitHub: @opscart
- Blog: @OpsCart
- Issues: Report issues
- Discussions: GitHub Discussions
- Senior DevOps Engineer
- IEEE Senior Member
- 15+ years IT experience
- 10+ years Cloud & DevOps specialization
- Published author on DZone and technical publications
If you find this guide helpful:
- ⭐ Star the repository
- 🔀 Fork for your own learning
- 📢 Share with your team
- 💬 Provide feedback
- 🤝 Contribute improvements
- Lab 11: Secrets Management - Tier 2 Deep-Dive (Linux VM Required)
- Process memory forensics and secret extraction
- Production Vault with TLS, HA, and dynamic secrets
- Zero-downtime secret rotation patterns
- Compliance audit logging (PCI-DSS, SOC 2)
- Lab 12: Container Registry Security
- Lab 13: Advanced Kubernetes Security Patterns
### Stay Updated
- Watch this repository for updates
- Follow [@opscart](https://github.com/opscart) on GitHub
- Join discussions in the Issues tab
---
**🎯 From fundamentals to advanced patterns, this guide has everything you need to secure your Docker deployments in production.**
---
**⭐ If you find this guide helpful, please star the repository!**
**🔒 Remember: Security is a journey, not a destination. Keep learning, keep improving!**