将环境变量传递给容器不起作用 [英] Passing environment variable to container is not working

查看:88
本文介绍了将环境变量传递给容器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下命令:

docker run -e "DB_HOST=thehost" --rm my_application echo $DB_HOST

但是什么也没显示.我原以为会显示主持人".

but it shows nothing. I was expecting "thehost" to be shown.

我尝试使用简单引号,双引号和不带引号.

I have tried with simple quotes, double quotes and without quotes.

我想念什么?我需要在my_aplication的Dockerfile中指定ENV参数吗?

What am I missing? Do I need to specify ENV parameter in my_aplication's Dockerfile?

如果我这样做:

docker run -e "DB_HOST=thehost" --rm my_application echo $PATH

它正确显示PATH值.但这忽略了我的环境变量.

It shows the PATH value properly. But it is ignoring my env var.

推荐答案

这里有两层:

  1. 您的本地shell会扩展命令;
  2. 哪个启动了一些Docker容器;
  3. 哪个会运行其他进程(但不一定是shell).

在第一个示例中

docker run ... echo $DB_HOST

您的本地shell在将变量引用传递给Docker之前就对其进行了捕获.

your local shell catches the variable reference before it ever gets passed on to Docker.

如果您明确将单引号

docker run ... echo '$DB_HOST'

Docker会找到/bin/echo(假设它存在于容器中)并以字符串$DB_HOST作为参数启动它,但是同样,由于Docker端不涉及任何shell,因此它会尽职地将该字符串打印为是.

Docker will find /bin/echo (assuming it exists in the container) and launch that with the string $DB_HOST as an argument, but again, since no shell is involved on the Docker side, it dutifully prints out that string as is.

您问题的直接答案是强制在Docker端安装一个外壳程序

The immediate answer to your question is to force there to be a shell on the Docker side

docker run -e DB_HOST=thehost --rm my_application \
  sh -c 'echo $DB_HOST'

更高的级别:

  • 如果您正在使用其他语言(而不只是shell命令)运行程序,他们将正常看到环境(Python的os.environ,Ruby的ENV,Node的process.env等.)
  • 如果您有任何复杂的东西,请将其写到shell脚本中,将其复制到映像中,然后运行可能更可维护的操作,并隐式涉及shell(第一行将显示#!/bin/sh)
  • 在您的Dockerfile中,如果您说CMD some command,则Docker会自动将其包装在shell中;相当于CMD ["sh", "-c", "some command"]
  • ENTRYPOINT也是一样,但是以这种方式使用它可能是一个错误
  • If you're running a program in some other language and not just a shell command, they'll see the environment normally (Python's os.environ, Ruby's ENV, Node's process.env, etc.)
  • If you have anything even a little complex, writing it into a shell script, COPYing that into an image, and running that is probably more maintainable, and implicitly involves a shell (the first line will say #!/bin/sh)
  • In your Dockerfile, if you say CMD some command, Docker will automatically wrap that in a shell; that is equivalent to CMD ["sh", "-c", "some command"]
  • The same is true for ENTRYPOINT, but it is probably a bug to use it that way

这篇关于将环境变量传递给容器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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