Code Reference

Env & Secrets

Docker · Reference cheat sheet

Env & Secrets

Docker · Reference cheat sheet


📋 Overview

Pass configuration with environment variables and inject secrets without baking them into image layers. Prefer runtime secrets over Dockerfile ENV for credentials.

🔧 Core concepts

MechanismUse
ENVNon-secret defaults in image
ARGBuild-time only (still visible in history if misused)
-e / environmentRuntime env
env_fileFile of KEY=VAL
BuildKit --secretSecret mounts during build
Orchestrator secretsSwarm/K8s/Compose secrets

💡 Examples

Runtime env:

docker run --rm -e DATABASE_URL="$DATABASE_URL" myapp:1.0.0

Compose env_file:

services:
  api:
    env_file:
      - .env
    environment:
      NODE_ENV: production

BuildKit npm token (sketch):

# syntax=docker/dockerfile:1
RUN --mount=type=secret,id=npm,target=/root/.npmrc npm ci
docker build --secret id=npm,src=$HOME/.npmrc -t myapp .

⚠️ Pitfalls

  • ENV SECRET=... in a Dockerfile is recoverable from image history.
  • Committing .env with production credentials is a common breach path.
  • docker history and layer caching can retain leaked build args.

On this page