How to set environment variable in docker containe

2019-08-23 10:43发布

问题:

I need to set some environment variable for all users and processes inside docker container. It should be set at container start, not in Dockerfile, because it depends on running environment.

So the simple Dockerfile

FROM ubuntu
RUN echo 'export TEST=test' >> '/root/.bashrc'

works well for interactive sessions docker run -ti test bash then env and there is TEST=test

but when docker run -ti test env there is no TEST

I was trying

RUN echo 'export TEST=test' >> '/etc/environment'
RUN echo 'TEST="test"' >> '/etc/environment'
RUN echo 'export TEST=test' >> /etc/profile.d/1.sh
ENTRYPOINT export TEST=test

Nothing helps.

Why I need this. I have http_proxy variable inside container automatically set by docker, I need to set another variables, based on it, i.e. JAVA_OPT, do it system wide, for all users and processes, and in running environment, not at build time.

回答1:

I would create a script which would be an entrypoint:

#!/bin/bash

# if env variable is not set, set it
if [ -z $VAR ];
then
    # env variable is not set
    export VAR=$(a command that gives the var value);
fi

# pass the arguments received by the entrypoint.sh
# to /bin/bash with command (-c) option
/bin/bash -c $@ 

And in Dockerfile I would set the entrypoint:

ENTRYPOINT entrypoint.sh

Now every time I run docker run -it <image> <any command> it uses my script as entrypoint so will always run it before the command then pass the arguments to the right place which is /bin/bash.

Improvements

The above script is enough to work if you are always using the entrypoint with arguments, otherwise your $@ variable will be empty and will give you an error /bin/bash: -c: option requires an argument. A easy fix is an if statement:

if [ ! -z $@ ];
then
    /bin/bash -c $@;
fi


回答2:

Setting the parameter in ENTRYPOINT would solve this issue.

In docker file pass parameter in ENTRYPOINT



标签: docker