在Docker容器中设置环境变量 [英] Set environment variables in Docker container

查看:289
本文介绍了在Docker容器中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我在做什么是最佳实践,还是有更好的方法:

I want to know if what I'm doing is considered best practice, or is there a better way:

我想拥有一个Docker映像,该映像在作为容器运行时将预定义一些环境变量.我想通过运行一些将导出这些变量的shell脚本来做到这一点.

I want to have a Docker image, which will have some environment variables predefined when run as a container. I want to do that by running some shell script that will export those variables.

我的dockerfile看起来像这样:

My dockerfile looks like this:

Dockerfile code..
..
..

RUN useradd -m develop
RUN echo ". /env.sh" >> /home/develop/.bashrc

USER develop


那是个好方法吗?

推荐答案

使用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.

这篇关于在Docker容器中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆