Interview Q&A / Docker & Kubernetes

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why should you never put passwords or API keys in a Dockerfile or image?

SHORT ANSWER

Anything baked into a layer, through ENV, ARG, COPY or RUN, can be read by anyone who can pull the image, using docker history or by unpacking layers. Inject secrets at runtime instead.

Explain it simply

Writing your ATM PIN on the back of the card: anyone who finds the card has the PIN. Image layers are permanent and shareable; whoever receives the image receives the secret.

Even if a later step deletes .env, the earlier layer still holds it. ENV API_KEY=abc is visible in docker inspect, and a --build-arg appears in docker history. Public images pushed to Docker Hub with leaked keys are scanned and abused by bots within minutes.

Better: pass secrets at runtime through environment variables from a secret store, Docker or Compose secrets mounted as files, or Kubernetes Secrets. For secrets needed during build, such as a private package token, use BuildKit's RUN --mount=type=secret, which is never stored in a layer. Also add .env to .dockerignore, and rotate any key that was ever committed.

Example

dockerfile
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
# docker build --secret id=npmrc,src=$HOME/.npmrc .

What to say in the interview

"Secrets baked into layers are readable by anyone with the image, even if deleted later. I inject them at runtime, use BuildKit secret mounts for build-time needs, keep .env out of the context, and rotate any leaked key."

Common mistakes

  • Deleting the secret in a later RUN and thinking it is gone.

#docker#security#secrets

Related questions

Practise more Docker & Kubernetes questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Docker & Kubernetes quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.