如何在所有用户启动容器时在Docker容器系统范围内设置环境变量? [英] How to set environment variable in docker container system wide at container start for all users?
问题描述
我需要为docker容器内的所有用户和进程设置一些环境变量。应该在容器启动时设置它,而不要在 Dockerfile
中设置它,因为它取决于运行环境。
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.
所以简单 Dockerfile
FROM ubuntu
RUN echo 'export TEST=test' >> '/root/.bashrc'
对于交互式会话非常有效
docker run -ti test bash
然后
env
并且有 TEST = test
works well for interactive sessions
docker run -ti test bash
then
env
and there is TEST=test
但是当 docker运行-ti test env
时,没有 TEST
我正在尝试
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
没有任何帮助
为什么我需要这个。我在由docker自动设置的容器内有 http_proxy
变量,我需要基于它设置另一个变量,即 JAVA_OPT
,请在整个系统范围内,对所有用户和进程以及在运行环境中(而不是在构建时)使用它。
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.
推荐答案
一个将作为入口点的脚本:
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 $@
在Dockerfile中,我将设置入口点:
And in Dockerfile I would set the entrypoint:
ENTRYPOINT entrypoint.sh
现在每次我运行 docker run -it< image> <任何命令>
它使用我的脚本作为入口点,因此将始终在命令之前运行它,然后将参数传递到正确的位置,即 / bin / bash
。
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
.
如果您始终将入口点与参数,否则您的 $ @
变量将为空,并给您一个错误 / bin / bash:-c:选项需要一个参数
。一个简单的解决方法是使用if语句:
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
这篇关于如何在所有用户启动容器时在Docker容器系统范围内设置环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!