Skip to content
shellhacks.dev
Docker

Set environment variables

Set an environment variable in a container with docker run -e NAME=value. Pass -e NAME with no value to copy the value from the calling shell.

1 min read
Summarize in AI

A container needs configuration through environment variables, and you do not want to bake them into the image.

Shell
export TOKEN=from-host
docker run --rm -e MODE=debug alpine:3.20 sh -c 'echo "MODE=$MODE TOKEN=${TOKEN-unset}"'
docker run --rm -e MODE=debug -e TOKEN alpine:3.20 sh -c 'echo "MODE=$MODE TOKEN=${TOKEN-unset}"'
Text
MODE=debug TOKEN=unset
MODE=debug TOKEN=from-host

-e NAME=value sets the variable, and -e NAME copies the variable from the environment of the docker client, which is why the second run sees from-host. The first run shows the default, because nothing is inherited from the host. See the docker run reference. The copying form keeps a secret out of the command line, and so out of ps and the shell history.

Environment variables are visible to docker inspect and to anyone who can read /proc/1/environ in the container, so they are a poor place for long lived secrets. A name that is not set in the client is not passed at all, instead of arriving empty.

Share

More snippets

Docker

Run a throwaway container

Run a container once and remove it on exit with docker run --rm. Without the flag every run leaves a stopped container behind, one per invocation.

1 min read
Docker

Mount read-only

Mount a host directory read-only into a container with -v "$PWD":/data:ro. A write from inside fails with a read-only file system error, even as root.

1 min read
Docker

Load environment from a file

Load variables from a file with docker run --env-file. The file is not parsed by a shell, so quotes stay in the value and a line with export fails.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.