Container environment variables
- Version
- 29
- Review
- Draft
Summary#
--env KEY=value sets a variable in a new container, --env KEY passes the value from your shell, and --env-file reads variables from a file. These options can replace values set by the image.
Syntax#
docker run --env KEY=value IMAGE
docker run --env KEY IMAGE
docker run --env-file app.env IMAGE
Example#
The example uses a local alpine:3 image.
(
set -eu
name="dlr-docker-commands-env-$$"
dir=$(mktemp -d)
trap 'docker rm -f "$name" >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT
printf '# settings\nAPP_MODE=file\nAPP_REGION=eu\nAPP_NAME="demo"\n' > "$dir/app.env"
APP_USER=from-shell
export APP_USER
docker run --pull never --rm --name "$name" --env-file "$dir/app.env" \
--env APP_MODE=flag --env APP_USER alpine:3 \
sh -c 'echo "mode=$APP_MODE region=$APP_REGION user=$APP_USER"'
docker run --pull never --rm --name "$name" --env-file "$dir/app.env" alpine:3 \
printenv APP_MODE APP_NAME
)
Expected output#
mode=flag region=eu user=from-shell
file
"demo"
Common mistakes#
A file read by docker run --env-file is not a shell script. Quotes become part of the value, as APP_NAME shows, and references to other variables are not expanded. When you pass --env KEY and KEY is absent from the client's environment, Docker unsets it in the container. Anyone with permission to inspect the container can read its configured variables.
Version applicability#
Checked with Docker Engine 29, where --env took precedence over the same key in --env-file. Compose env files have their own parsing and precedence rules.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0