Secrets at build time and run time

Intermediate · 4 min

How secrets leak into images through ARG, ENV and deleted files, why environment variables are a weak place for them, and how Compose mounts secrets as files.

Before thisBuild arguments and environment variablesCache mounts and build secretsThe Compose file: services, networks and volumes

Infisical · 4 min

Secrets at build time and run time

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by InfisicalReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An image is shareable by design. Anything in a layer or in the image config can be read by anyone who can pull it, without running a container.
  • `ARG` and `ENV` values are recorded in the image config, and every instruction appears in its history. Docker's build check SecretsUsedInArgOrEnv flags secret-looking names.
  • Deleting a file in a later layer only adds a whiteout. The earlier layer still contains the file, byte for byte.
  • At build time, use secret mounts so the secret exists only for one RUN step and never reaches a layer.
  • At run time, environment variables are visible through `docker inspect`, to child processes, and in crash dumps and debug pages. Files are a better delivery route.
  • Compose's `secrets` mount each secret as a file at /run/secrets/<name>. Many official images read `*_FILE` variables, such as POSTGRES_PASSWORD_FILE.
  • Keep secret values out of the repository and out of the image. The image carries code and the runtime supplies secrets, so one image can serve every environment.

Images are meant to be copied

An image exists to be pushed, pulled and run anywhere. That is exactly why secrets don’t belong in it. Whatever is in a layer or in the image’s metadata goes to every registry, cache, laptop and CI runner that ever pulls it, and stays in old tags long after you rotate the key.

There are two moments when a secret is needed. At build time, to fetch private dependencies. At run time, to connect to a database or an API. Each has its own way of leaking.

Build-time leaks

ARG and ENV are metadata

Every image has a config document, a few kilobytes of JSON, that records its environment and the history of the instructions that made it. You don’t need to pull any layers to read it. I fetched the config of postgres:18 from Docker Hub’s registry API. Its history lists all 23 instructions, including every ENV line in full:

ENV GOSU_VERSION=1.20
ENV PG_MAJOR=18
ENV PG_VERSION=18.7-1.pgdg13+5
ENV PGDATA=/var/lib/postgresql/18/docker

Those are harmless. A ENV API_KEY=... would be just as visible, to anyone who runs docker history --no-trunc or docker inspect on the image, or fetches the config from the registry. ARG is no better: build arguments used by RUN steps end up in the image’s metadata. BuildKit’s own build check, SecretsUsedInArgOrEnv, warns about ARG or ENV names that look like secrets, and its documentation states the reason: they “persist in the final image”.

Deleting a file doesn’t remove it

The second classic mistake:

COPY .npmrc /app/.npmrc
RUN npm ci && rm /app/.npmrc     # looks clean, isn't

Each instruction that changes files makes a layer, a tar archive, as layers, OverlayFS and copy-on-write explains. Deleting a file in a later layer doesn’t edit the earlier one. It adds a whiteout, an empty entry named .wh.<filename>, which tells the union filesystem to hide the file.

I wrote a small Python stand-in for those two steps: a first tar layer containing app/.npmrc with a fake token, a second containing installed packages and app/.wh..npmrc. Applying the layers the way OverlayFS presents them:

files the container sees: ['app/node_modules/left-pad/index.js']
layer1 still holds: //registry.npmjs.org/:_authToken=npm_FAKE0000000000000000

The running container can’t see the file. Anyone with the image can untar the first layer and read it. Squashing the steps into one RUN helps only if the secret never touched a separate COPY layer, and multi-stage builds help only if the secret stays in a stage you don’t ship.

The fix: secret mounts

BuildKit can mount a secret into a single RUN step as a temporary file that is never written to a layer or recorded in metadata:

RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm ci
docker build --secret id=npmrc,src=$HOME/.npmrc .

The details, including SSH agent forwarding for private Git repositories, are in cache mounts and build secrets. Also make sure .env, .npmrc and key files are in .dockerignore, so a broad COPY . . can’t sweep them in.

Run-time leaks

What’s wrong with environment variables

Environment variables are the twelve-factor default, and they are fine for configuration. For secrets they are a weak home:

  • docker inspect on the container shows them in Config.Env, to anyone with access to the Docker API.
  • Every child process the app starts inherits them.
  • Crash reporters, debug pages and “print the environment” log lines are a common way they leak.
  • In Compose they tend to end up typed into compose.yaml, then committed.

A file is safer. It has permissions, it isn’t inherited, and the app reads it once.

Compose secrets

Compose declares secrets at the top level, from a file or from a host environment variable, and grants them per service:

services:
  db:
    image: postgres:18
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
  api:
    image: registry.example.com/api:1.4.2
    secrets:
      - db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt     # not in git

Each granted secret appears as a file at /run/secrets/<name>. The docs note that for file: sources Compose uses a bind mount, so the uid, gid and mode options are silently ignored and the file keeps its host permissions. They work only for environment: sources.

The *_FILE convention is what makes this work with off-the-shelf images. I extracted docker-entrypoint.sh from the postgres:18 image. Its file_env function reads POSTGRES_PASSWORD_FILE if set, refuses to start if both the variable and the _FILE form are set, and before starting the server it runs unset "${!POSTGRES_@}", so the password variables don’t reach the postgres process at all. With the _FILE form, docker inspect shows only the path.

For your own code, read the file at startup:

from pathlib import Path
db_password = Path("/run/secrets/db_password").read_text().strip()

Where the secret file comes from on a server, a secrets manager, a CI deploy step or an encrypted file, is a separate decision, covered in DevOps’ secrets management for infrastructure.

About the video

The embed is the first 4 minutes 10 seconds of “The Best Way to Manage .env Variables in Docker (Compose, Secrets & More)” from Infisical, July 2026. The description names this lesson’s three build-time mistakes, a .env swept in by COPY, an ENV line and a build argument, and the chapters in the clip are “The dangers of baked secrets”, “Analyzing security failures”, “The impact of secret sprawl” and “Runtime secret injection”. The video goes on to configure Infisical’s own product, which is why the clip stops there. Infisical sells a secrets manager, so treat the framing accordingly. YouTube reports no audio language, so English was judged from the channel and English captions. Nana’s chapter on Compose secrets in deeper shows the secrets: syntax in a full project.

What was run: the postgres:18 image config was fetched from Docker Hub and its history read, its entrypoint script was extracted from a layer and read, and a Python stand-in built two tar layers to show a whiteout hiding but not removing a file. No image was built and no container run, since no daemon was available. The secret mount and Compose behaviour are from Docker’s documentation, checked 2026-11-28.

Where this fits

Your image no longer leaks secrets. It may still ship known vulnerabilities in its packages: scanning images for vulnerabilities.

Check yourself

  1. 01A Dockerfile does COPY .npmrc . then RUN npm ci && rm .npmrc in a later step. Is the token in the image?

    Yes. COPY created a layer containing .npmrc, and the rm in a later layer only adds a whiteout entry. Anyone who pulls the image can extract the earlier layer and read the token.

  2. 02Why is ARG NPM_TOKEN passed with --build-arg not a safe way to give a build a token?

    Build arguments used by RUN steps are recorded in the image's metadata and history, which anyone who can pull the image can read. Use a secret mount instead.

  3. 03You pass DB_PASSWORD with environment: in compose.yaml. Where else, outside the app, can it be read?

    docker inspect on the container shows it in Config.Env, and any child process inherits it; it can also turn up in logs, crash reports or a framework's debug page that dumps the environment.

  4. 04How do you give the official postgres image its password without putting the password in an environment variable?

    Declare a Compose secret from a file, grant it to the db service, and set POSTGRES_PASSWORD_FILE=/run/secrets/db_password. The entrypoint reads the file and Config.Env only shows the path.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark