Docker Secrets

Applications need sensitive values such as database passwords, API keys, and certificates. Storing these values in the wrong place exposes them to anyone who can read an image or inspect a container. Docker offers safer ways to deliver secrets, and a few simple rules keep them out of harm's way.

Where Secrets Should Never Live

Place                       Why it fails
--------------------------  -------------------------------------------
Dockerfile ENV line         saved in the image; shown by docker history
COPY of a .env file         saved inside an image layer forever
Source code                 shared with everyone who clones the repo
Command line arguments      visible in process lists and shell history

Deleting a secret in a later Dockerfile line does not remove it. Each layer stays in the image, and anyone can extract earlier layers.

RUN echo "key=abc123" > /app/key     layer 1 holds the secret
RUN rm /app/key                      layer 2 hides it; layer 1 still has it

The Locker Analogy

A secret works like a valuable item in a bank locker. The bank hands the key to the right person at the right moment, and the item never sits on a public shelf. Docker secrets follow the same idea: the value reaches the container only when it runs and only for the containers that need it.

Runtime Environment Variables

Passing a variable at run time keeps it out of the image.

docker run -e DB_PASSWORD="$DB_PASSWORD" my-app

This method works for simple cases. The value still appears in docker inspect output for that container, and child processes inherit it. Use it for low-risk settings and prefer files for real secrets.

Secrets as Files in Compose

Compose can mount a secret as a read-only file inside the container at /run/secrets.

services:
  api:
    image: my-api
    secrets:
      - db_password
    environment:
      DB_PASSWORD_FILE: /run/secrets/db_password

secrets:
  db_password:
    file: ./secrets/db_password.txt

The application reads the password from the file path. Many official images, including Postgres and MySQL, support variables ending in _FILE for this purpose.

Host file                    Container
./secrets/db_password.txt -> /run/secrets/db_password  (read-only)

Swarm Secrets

Docker Swarm stores secrets encrypted inside its cluster database and sends them only to the services that request them.

echo "S3cur3Pass" | docker secret create db_password -
docker service create --name api --secret db_password my-api

The secret appears as a file in memory, so it never touches the container disk.

Build-Time Secrets

Builds sometimes need a token, such as a key for a private package registry. BuildKit mounts a secret for a single RUN instruction and leaves nothing behind.

# syntax=docker/dockerfile:1
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) npm install

docker build --secret id=npm_token,src=./npm_token.txt -t my-app .

Good Habits

  1. Keep secrets out of Dockerfiles and source control.
  2. Add secret files to .gitignore and .dockerignore.
  3. Give each service only the secrets it needs.
  4. Rotate secrets on a regular schedule.
  5. Use a dedicated secret manager for production, such as a cloud provider vault.

If a Secret Leaks

Treat the value as compromised. Create a new secret, update the application, and revoke the old value. Removing the file from the image does not help once someone has pulled the image.

Common Mistakes

  • Printing environment variables in application logs.
  • Using the same password across development and production.
  • Pushing an image with a baked-in key to a public registry.

Real-World Scenario

A student publishes a Docker image to a public registry as a portfolio project. The Dockerfile includes a line that copies a .env file holding a cloud access key. Within hours, automated bots scan public registries, find the key, and run expensive services on the student's account. The student receives a large bill and spends days cleaning up.

Three small habits would have prevented the incident: a .dockerignore entry for .env files, a runtime secret instead of a copied file, and a scan for secrets before every push. Several scanning tools search images and source code for passwords and keys, and they run fast enough to fit into any build.

Choosing a Method

Situation                          Method
---------------------------------  -----------------------------
Local development                  .env file kept out of Git
Single server with Compose         secrets mounted as files
Swarm cluster                      docker secret
Private package during build       BuildKit secret mount
Large production environment       cloud or vault secret manager

Start with the simplest method that keeps the value out of images and source control, and move to a stronger tool as the project grows.