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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With