How do you prevent secrets from ending up in Docker images?
IntermediateConceptGitleaks
Answer
Short answer
Never COPY secret files or put secrets in ENV or ARG — they're stored in image layers that anyone who pulls the image can read. Use a .dockerignore, BuildKit secret mounts for build-time secrets, and inject runtime secrets via environment variables or mounted files from the orchestrator. Scan images for secrets too.
Wrong
COPY .env . # ❌ file baked into a layer
ARG NPM_TOKEN # ❌ visible in image history
ENV DB_PASSWORD=S3cret! # ❌ visible with docker inspect
docker history --no-trunc myimage # shows ARG values and commands
Right
# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm_token \
NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci # secret never stored in a layer
docker build --secret id=npm_token,env=NPM_TOKEN -t shop-web .
# .dockerignore
.env
*.pem
.git
At runtime: Kubernetes Secrets / ECS secrets / Key Vault references → env vars or files.
Scan the image
trivy image --scanners secret shop-web:1.2.0
What to say in the interview
"Secrets never go into COPY, ENV or ARG because layers and history are readable. We use .dockerignore, BuildKit secret mounts for build-time tokens, runtime injection from the orchestrator, and Trivy's secret scanner on built images."
More on Gitleaks
What is Gitleaks and how do you use it?BeginnerWhat is a secret leak and why is it dangerous?BeginnerWhat is Gitleaks?BeginnerHow do you scan a repository's full history with Gitleaks and create a report?BeginnerHow do you stop secrets before they're committed using a pre-commit hook?BeginnerHow do you run Gitleaks in a CI pipeline and fail the build on findings?Beginner