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
ENVare stored in the image config. ARGvalues used inRUNcan be seen withdocker history.- A
.envfile 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,ARGorCOPY. ENVandARGvalues 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.
Read more