Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dockerfile: create ENV variable that a USER can see?

Is there a way to set an ENV variable for a custom USER in a docker file?

I am trying the following:

FROM some_repo/my_base_image
ENV FOO_VAR bar_value
USER webapp
# ... continued (not important)

But my "webapp" user can not see the "FOO_VAR" variable. HOWEVER, my root user CAN.

Any help would be appreciated.

like image 422
niknak Avatar asked Sep 14 '15 21:09

niknak


People also ask

Can Dockerfile access environment variables?

Dockerfile provides a dedicated variable type ENV to create an environment variable. We can access ENV values during the build, as well as once the container runs. Let's see how we can use it to pass value to our greetings script. There are two different ways to do it.

How do I pass an environment variable in Dockerfile?

Use -e or --env value to set environment variables (default []). If you want to use multiple environments from the command line then before every environment variable use the -e flag. Note: Make sure put the container name after the environment variable, not before that.

How do I create a variable in Dockerfile?

You can use ARG variable defaultValue and during the run command you can even update this value using --build-arg variable=value . To use these variables in the docker file you can refer them as $variable in run command.


2 Answers

Any user can see the environment variables:

$ cat Dockerfile
FROM debian

ENV foo bar
RUN groupadd -r am && useradd -r -g am am
USER am
$ docker build -t test .
...
$ docker run test bash -c 'echo $foo'
bar

So that's not what the problem is. It may be that your process forked a new environment, but I can't be sure as you haven't shared how you're checking the value.

like image 144
Adrian Mouat Avatar answered Sep 21 '22 23:09

Adrian Mouat


If you switch user context using su within the dockerfile's ENTRYPOINT, CMD or docker exec ... using the form below you enter a new shell process for the given username that does not persist your original environment variables provided by the ENV targets through dockerfile, docker-compose yaml, or docker run -e ...

> su - username -c "run a process"

To avoid this behavior simply remove the dash - from the call like so:

> su username -c "run a process"

Your assigned docker environment variables will now persist.

like image 25
Drone Brain Avatar answered Sep 21 '22 23:09

Drone Brain