Docker Community Forums

Share and learn in the Docker community.

Question about exporting enviromental variables to containers using an entrypoint script

Assume a simple Dockerfile

FROM php-fpm:8
RUN chmod +x
CMD ["php-fpm"]

In the entry-point script I just export a variable and print the environment


set -e

export FOO=bar

env // just print the environment while entrypoint is running

Then I build the image as myimage and use it to deploy a stack in docker swarm mode

docker stack deploy -c docker-compose.yml teststack

// The docker-compose.yml file used is the following:

  image: myimage:latest
    APP_ENV: production

Now the question: If a check the logs of the app service I can see (because of the env command in the entrypoint) that the FOO variable is exported

docker service logs teststack_app 

teststack_app.1.nbcqgnspn1te@xxx    | PWD=/var/www/html
teststack_app.1.nbcqgnspn1te@xxx    | FOO=bar
teststack_app.1.nbcqgnspn1te@xxx    | HOME=/root

However if I login in the running container and manually run env the FOO variable is not shown

docker container exec -it teststack_app.1.nbcqgnspn1tebirfatqiogmwp bash

root@df9c6d9c5f98:/var/www/html# env // run env inside the container

// No FOO variable :(

What I am missing here?

You are missing that the process that is running ./ is not the same process that is running the bash shell that you are execing into. Two completely different processes with two different environments. Only the process of ./ and any subprocesses will see FOO

If you want FOO to be globally available you will have to pass it in when you run the container by adding it to your docker-compose.yml file:

  image: myimage:latest
    APP_ENV: production
    FOO: bar

If you want this to be dynamic, you can use environment variables in your docker-compose.yml file:

  image: myimage:latest
    APP_ENV: production
    FOO: ${FOO}

This will pick up FOO from the environment that runs docker-compose

You must inject your host environment variable (client_token) into the docker container using ‘-e’ when running:

docker run -it --rm -e client_token=
This works for example with this kind of entrypoint:

export TOKEN=client_token echo "The TOKEN is: {TOKEN}"

do stuff …

If you don’t know the token value when the container was run, you should inject during attachment (docker exec) and perform required operations inside, but probably it is not valid for you if running container already needed that information.

docker exec -it -e TOKEN=