Skip to content

Instantly share code, notes, and snippets.

@dotspencer
Last active March 28, 2023 13:58
Show Gist options
  • Save dotspencer/7565e05a511b714a07923ff91ea82e58 to your computer and use it in GitHub Desktop.
Save dotspencer/7565e05a511b714a07923ff91ea82e58 to your computer and use it in GitHub Desktop.
Three ways to add env variables to a running docker container

1. Add to image at build-time

in .gitlab-ci.yml:

docker build --build-arg VAR_NAME="$VAR_NAME"

$VAR_NAME references a stored env variable from Gitlab CI settings.

in Dockerfile:

ARG VAR_NAME
ENV VAR_NAME=$VAR_NAME

It's currently not possible to set an env variable directly. The workaround is passing it as an arg first and then setting the env from the arg value. The duplicate names isn't a problem since env variables take precedence and are used instead of the arg value when calling $VAR_NAME. These env variables set become "baked in" to the image which prevents you from running in different environments with the same image.

2. Pass from host at run-time

on host command line:

docker run -e VAR_NAME

This will tell docker to access the host's env variable VAR_NAME and set the same env variable on the running container.

3. Explicitly define at run-time (preferred)

docker run -e "VAR_NAME=VAR_VALUE"

Same as above but allows you to define the value explicitly. Seems like this would be the best way if you want to ssh into a server and run the docker run command to update and start a new container for an app. This would allow creating a command string to pass through ssh using something like -e "VAR_NAME=$VAR_NAME" to interpolate the value from the Gitlab CI settings.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment