且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Docker容器中设置环境变量

更新时间:2022-01-17 09:08:33

使用Dockerfile ENV 指令比将环境变量放入文件中更有用.

Using the Dockerfile ENV directive would be much more usable than putting environment variables into a file.

ENV SOME_VARIABLE=some-value
# Do not use .bashrc at all
# Do not `RUN .` or `RUN source`

大多数使用Docker的方法都不涉及运行诸如 .bashrc 之类的shell点文件.在此添加设置通常不会产生任何效果.在Dockerfile中, RUN 指令中的所有环境变量设置都会在该行的末尾丢失,包括您使用shell .命令(或等效命令)读取的文件.但非标准的 source ).

Most ways to use Docker don't involve running shell dotfiles like .bashrc. Adding settings there won't usually have any effect. In a Dockerfile, any environment variable settings in a RUN instruction will get lost at the end of that line, including files you read in using the shell . command (or the equivalent but non-standard source).

例如,给定您显示的Dockerfile,像这样的 docker run 调用根本不会调用shell,也不会读取 .bashrc 文件:

For example, given the Dockerfile you show, a docker run invocation like this never invokes a shell at all and never reads the .bashrc file:

docker run the-image env \
  | grep A_VARIABLE_FROM_THE_BASHRC

对此有一些解决方法(我的回答

There are some workarounds to this (my answer to How to source a script with environment variables in a docker build process? describes a startup-time entrypoint wrapper) but the two best ways are to (a) restructure your application to need fewer environment variables and have sensible defaults if they're not set, and (b) use ENV instead of a file of environment-variable settings.