Environment variables and secrets

Docker · lesson 9 of 31 · 4 min read

Configure a container from the outside and keep credentials out of your image history.

Open this lesson in the learning hub

Key points

  • ENV is baked into the image and readable by anyone running docker image history. Never put a secret there.
  • ARG is build-time only, but it still lands in image metadata. Also not a secret.
  • At runtime use -e KEY=value or --env-file. Nothing is written into the image.
  • Spring Boot binds SPRING_DATASOURCE_URL to spring.datasource.url automatically. Relaxed binding, no code required.
  • For build-time credentials use BuildKit: RUN --mount=type=secret,id=.... The value never touches a layer.
  • In production prefer secrets mounted as files under /run/secrets. Env vars leak into logs, crash dumps and child processes.

Example

# configuration at runtime, nothing baked in
docker run -d -p 8080:8080 \
  -e SPRING_PROFILES_ACTIVE=prod \
  -e SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/app \
  --env-file ./secrets.env \
  myapp:1.0

# build-time secret that never reaches a layer
# in the Dockerfile:
#   RUN --mount=type=secret,id=m2settings,target=/root/.m2/settings.xml \
#       mvn -B -q package -DskipTests
docker build --secret id=m2settings,src=$HOME/.m2/settings.xml -t myapp:1.0 .

ENV and ARG are public. Runtime env vars and BuildKit secrets are not.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Docker course, and every lesson in it is listed on the Docker contents page.