0

I am trying to define some pre-set ENV variables for a user to select during a "docker RUN", but they do not persist on the container as expected.

I tried defining the ENV in the Dockerfile itself, which works for the default, but you cannot change it on-the-fly to other presets. You CAN, however, change it to other plaintext outputs.

Dockerfile :

ENV SH_HELLO="Hello World!" SH_BYE="Goodbye, cruel world!"
ENV ENV_PHRASE=${SH_HELLO}
COPY run.sh .
RUN chmod u+x run.sh
CMD bash ./run.sh

run.sh :

#!/bin/bash
echo "${ENV_PHRASE}"

This prints "Hello World!" as expected.

If I run a terminal in the container and run "env", I DO get all of the variables.

sh-4.2# env
SH_BYE=Goodbye, cruel world!
SH_HELLO=Hello World!
ENV_PHRASE=Hello World!

However, if I run either of these :

docker run -it -e ENV_PHRASE=${SH_BYE}
docker run -it -e ENV_PHRASE=${SH_HELLO}

It returns blank,

sh-4.2#

sh-4.2#

and the "env" in the container shows this :

sh-4.2# env
SH_BYE=Goodbye, cruel world!
SH_HELLO=Hello World!
ENV_PHRASE=

The desired result is that a user can look at some list of variables that I provide, select one, and have the docker deployment use that variable without having to manually define their own or use a custom one.

i.e.

docker run -e SOMEENV=$TEMPLATE1
docker run -e SOMEENV=$TEMPLATE2
docker run -e SOMEENV=$TEMPLATE3
docker run -e SOMEENV="custom config"

Meanwhile defined elsewhere :

TEMPLATE1=config1
TEMPLATE2=config2
TEMPLATE3=config3

1 Answer 1

1

First of all when you do this:

docker run -it -e ENV_PHRASE=${SH_BYE}

docker looks for the environment variable in the context where it runs (i.e. the host machine), not inside the image or container.

To be honest I cannot see a use-case for what you are trying to achieve, but how I normally do is I provide a .env file the users can personalise:

docker run --env-file .env ....

This has already the variable names and the users can supply their own values. And that would be the list of variables you want.

There are more sophisticated solutions for supplying key-value pairs like Consul or Vault that you can also look at in the future.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.