CodePark/ questions / Environment, config & secrets
START PRACTICINGPRACTICE
Backend question · Docker › Environment, config & secrets

How should secrets be handled with Docker, both at build time (like a private npm token) and at runtime (like a database password)?

Never put secrets in the image. Use BuildKit secret mounts at build time, and inject secrets when the container starts at runtime.

Why secrets leak into images:

  • Values set with ENV are stored in the image config.
  • ARG values used in RUN can be seen with docker history.
  • A .env file you copy in stays in a layer, even if you delete it later.

Build time: use BuildKit secret mounts. For example: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci, built with docker build --secret id=npmrc,src=.npmrc .. The file exists only during that RUN step. Docker does not write it to any layer.

Runtime: inject secrets when the container starts. Options:

  • environment variables from your platform
  • a secret manager
  • Compose or Swarm secrets, mounted as files under /run/secrets/
  • Kubernetes Secrets

Secrets stored as files are less likely to leak than environment variables. Environment variables can leak through docker inspect, logs or child processes.

  • Never put secrets in the image with ENV, ARG or COPY.
  • ENV and ARG values are visible in image metadata or history.
  • At build time, use RUN --mount=type=secret.
  • At runtime, inject secrets via environment variables, secret files or a secret manager.
  • Compose secrets appear as files under /run/secrets.