Docker · Containers in practice

How do you handle secrets in Docker builds and at runtime?

HardsecretsbuildkitsecurityUpdated Oct 2026
Quiz this track

Short answer

Never bake secrets into image layers or ENV. Use BuildKit secret mounts for build-time credentials and an external secret manager or mounted files at runtime.

A secret copied into an image remains in the layer even if a later instruction deletes it. ARG values can also appear in image history. Runtime secrets should come from a secret manager, an orchestrator secret object, or a file mount, not from the image.

dockerfile
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
  npm ci --omit=dev
BuildKit mounts the secret only for that RUN and does not persist it in a layer.

Runtime options

  • Mount a secret file read-only and read it at startup
  • Use the platform's secret store, such as Kubernetes Secrets with encryption at rest
  • Fetch from Vault or a cloud secret manager with workload identity
  • Restrict who can read the secret and rotate it on a schedule
  • Avoid passing secrets on the command line, where they appear in process listings

Environment variables are convenient but leak through inspect, crash reports and child processes. If you must use them, treat the exposure as accepted risk and keep the value short-lived.

Removing a secret in a later layer does not remove it from the image. The earlier layer still contains the bytes and can be extracted by anyone who can pull the image.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is deleting a secret in a later layer insufficient?
  2. 2How does BuildKit prevent a build secret from persisting?
  3. 3Are Kubernetes Secrets encrypted by default?
  4. 4How would you rotate a runtime secret without downtime?

Say it in the interview

I never copy secrets into an image or pass them as build arguments, because they persist in layers or history. For builds I use BuildKit secret mounts, and at runtime I mount files from a secret manager or use the orchestrator's secret store with workload identity. I also plan rotation and restrict read access, since a leaked secret is only useful until it is rotated.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.