Environment variables and secrets
Configure a container from the outside and keep credentials out of your image history.
Open this lesson in the learning hubKey points
ENVis baked into the image and readable by anyone runningdocker image history. Never put a secret there.ARGis build-time only, but it still lands in image metadata. Also not a secret.- At runtime use
-e KEY=valueor--env-file. Nothing is written into the image. - Spring Boot binds
SPRING_DATASOURCE_URLtospring.datasource.urlautomatically. 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.