在 Ubuntu 的运行级别脚本中选择传递给 docker 容器的环境变量

Picking environment variables passed to docker container in Runlevel Scripts in Ubuntu

我知道如何将环境变量传递给 docker 容器。喜欢

sudo docker run  -e ENV1='ENV1_VALUE' -e ENV2='ENV2_VALUE1' ....

如果我在 docker 容器中从 shell 编写 运行 脚本,我就能成功地选择这些变量。但是 docker 实例的 运行 级脚本无法看到传递给 docker 容器的环境变量。最终,所有 services/daemon 都以我不想要的默认配置开始。

请提出一些解决方案。

在您的 Dockerfile 中,您可以选择在运行前指定环境变量。

Dockerfile

FROM ubuntu:16.04
ENV foo=bar
ENV eggs=spam
RUN <some runtime command>
CMD <entrypoint>

查看 at the docker environment replacement docs 了解更多信息。

运行级别脚本将无法读取环境变量,我认为这是一件好事。

您可以尝试将环境变量放在主机上的一个文件中,将其挂载到 docker 容器中的一个文件(例如 /etc/init.d/ 下)。并更改 docker 图像的初始化脚本以在 运行 您的脚本之前获取已安装的文件。

You can manage your run level services to pick environment variables passed to 
Docker instance.

For example here is my docker file(Dockerfile):

....
....
# Adding my_service into docker file system and enabling it.
ADD my_service /etc/init.d/my_service
RUN update-rc.d my_service defaults
RUN update-rc.d my_service enable
# Adding entrypoint script
COPY ./entrypoint.sh /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

# Set environment variables.
ENV HOME /root
# Define default command.
CMD ["bash"]


....


Entrypoint file can save the environment variables to a file,from which
you service(started from Entrypoint script) can source the variables.

entrypoint.sh contains:
#!/bin/bash -x
set -e
printenv | sed 's/^\(.*\)$/export /g' > /root/project_env.sh
service my_service start
exec /bin/bash

Inside my_service, I am sourcing the variables from /root/project_env.sh like:
#!/bin/bash
set -e
. /root/project_env.sh



I hope it solve your problem. This way you need NOT to depend on external file system, provide your are passing variables to your docker instance at the time of running it.