Skip to content
shellhacks.dev
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
Summarize in AI

A dozen variables belong in a file, and the file you already have for the application looks like shell syntax.

Shell
printf 'MODE=debug\nNAME="quoted"\n# a comment\nEMPTY=\n' > app.env
docker run --rm --env-file app.env alpine:3.20 sh -c 'echo "[$MODE] [$NAME] [$EMPTY]"'
printf 'export MODE=debug\n' > shell.env
docker run --rm --env-file shell.env alpine:3.20 sh -c 'env | grep -i mode'
Text
[debug] ["quoted"] []
docker: --env-file: invalid env file (shell.env): variable 'export MODE' contains whitespaces

Run 'docker run --help' for more information

The --env-file format is one NAME=value per line, with # lines ignored, and the value is taken literally. The second variable shows the catch: the double quotes are part of the value, unlike in a Compose file or a shell script. The format is described in the docker run reference. A line that begins with export is rejected by the client, which reports that the variable name export MODE contains whitespace.

Leave the quotes out of the file, or use a Compose env_file, whose parser handles them. A bare name with no equals sign copies the variable from the host, as with -e. The file is read by the client at start, so later edits do not reach a running container.

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

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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.