Docker Community Forums

Share and learn in the Docker community.

How to export a variable that will stay after I logout of the container?

Say we need to set following environment variable in a running container:


we have tried setting it using the export command for example like:

$ docker exec my-container sh -c ‘export APP_ENV=PROD’

and also with the -it option:

$ docker exec -it my-container /bin/bash


but the problem is that it disappears the moment we logout of the container. How can we set it permanently?

You can
A: Use the ENV keyword in your dockerfile when building the image if you know the value for APP_ENV while building the image or
B: Use the docker run flag -e APP_ENV=PROD to set an env inside a container.

Your way with docker exec doesn’t work because exec /bin/bash opens a new shell in which you set the env. When you leave the exec shell the shell you set your env in stops and thus the env is lost. (Your default container application couldn’t access the env variable anyways.)

You can add it to your shell configuration file, e.g. $HOME/.bashrc or more globally in /etc/environment. After adding these lines the changes won’t reflect instantly in GUI based system’s you have to exit the terminal or create a new one and in server logout the session and login to reflect these changes.

Sorry if my question was not clear but I am not looking to recreate the container. I have a running container and want to be able to set env variable in it so that the process running inside the container can see that env variable. I can stop and restart the container but I need a solution that will not require me to recreate the container.

derteufelqwe gave you the answer. You can run your container like docker run -e APP_ENV=PROD and you will have your variable available there.