Secrets and Sensitive Data in Images
What you'll learn: How to detect hardcoded secrets, API keys, and credentials accidentally embedded in container image layers.
The Hidden Danger in Layers
Container images are built in layers—each command in your Dockerfile creates a new layer. Even if you delete a secret in a later layer, it still exists in an earlier layer's history. Anyone with access to the image can extract these layers and find credentials you thought were removed. It's like crossing out sensitive information with a marker instead of shredding the page—the data is still there.
Common mistakes include hardcoding database passwords, embedding AWS keys in environment variables, or copying .env files during the build process.
Detection Tools
truffleHog and GitLeaks are specialized tools that scan container images (and git repositories) for secrets using pattern matching and entropy analysis:
- truffleHog searches for high-entropy strings and known secret patterns across all image layers
- GitLeaks uses configurable rules to identify API keys, tokens, and credentials based on regex patterns
Both tools can scan Docker images directly:
# Scan an image with truffleHog
trufflehog docker --image myapp:latest
# Scan with GitLeaks
gitleaks detect --source /path/to/image/layers
These tools examine every layer's filesystem, configuration, and environment variables, flagging potential secrets before the image reaches production or a public registry.
Prevention is Key
Beyond detection, never bake secrets into images. Use runtime secret injection through Kubernetes secrets, Docker secrets, or secret management services. Build images with placeholder values only.
Key Takeaway: Hardcoded secrets persist in image layers even after deletion; use truffleHog and GitLeaks to scan images for leaked credentials before deployment, and always inject secrets at runtime rather than build time.