我知道如何将环境变量传递给 docker 容器。像
sudo docker run -e ENV1='ENV1_VALUE' -e ENV2='ENV2_VALUE1' ....
如果我从 docker 容器内的 shell 运行脚本,我能够成功选择这些变量。但是 docker 实例的运行级别脚本无法看到传递给 docker 容器的环境变量。最终,所有服务/守护程序都以我不想要的默认配置开始。
请为此提出一些解决方案。
在您的 Dockerfile 中,您可以选择在运行前指定环境变量。
Dockerfile
FROM ubuntu:16.04
ENV foo=bar
ENV eggs=spam
RUN <some runtime command>
CMD <entrypoint>
查看docker 环境替换文档以获取更多信息。
运行级别脚本将无法读取环境变量,我认为这是一件好事。
您可以尝试将环境变量放在主机上的文件中,将其挂载到 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 \1/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.