在 Dockerfile 中获取环境变量值 [英] Get environment variable value in Dockerfile

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

问题描述

我正在为 ruby​​ 应用构建一个容器.我的应用程序的配置包含在环境变量中(使用 dotenv 加载到应用程序内).

I'm building a container for a ruby app. My app's configuration is contained within environment variables (loaded inside the app with dotenv).

这些配置变量之一是应用程序的公共 ip,它在内部用于建立链接.我需要添加一个 dnsmasq 条目,将这个 ip 指向容器内的 127.0.0.1,这样它就可以获取应用程序的链接,就好像它没有被容器化一样.

One of those configuration variables is the public ip of the app, which is used internally to make links. I need to add a dnsmasq entry pointing this ip to 127.0.0.1 inside the container, so it can fetch the app's links as if it were not containerized.

因此,我试图在我的 Dockerfile 中设置一个 ENV,它将环境变量传递给容器.

I'm therefore trying to set an ENV in my Dockerfile which would pass an environment variable to the container.

我尝试了一些东西.

ENV REQUEST_DOMAIN $REQUEST_DOMAIN
ENV REQUEST_DOMAIN `REQUEST_DOMAIN`

所有东西都传递REQUEST_DOMAIN"字符串而不是环境变量的值.有没有办法将环境变量值从主机传递到容器?

Everything passes the "REQUEST_DOMAIN" string instead of the value of the environment variable though. Is there a way to pass environment variables values from the host machine to the container?

推荐答案

你应该使用 ARG 指令 用于此目的.

You should use the ARG directive in your Dockerfile which is meant for this purpose.

ARG 指令定义了一个变量,用户可以在构建时使用 --build-arg = 使用 docker build 命令将其传递给构建器; 标志.

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

所以你的 Dockerfile 会有这一行:

So your Dockerfile will have this line:

ARG request_domain

或者如果您更喜欢默认值:

or if you'd prefer a default value:

ARG request_domain=127.0.0.1

现在您可以在 Dockerfile 中引用此变量:

Now you can reference this variable inside your Dockerfile:

ENV request_domain=$request_domain

然后你将像这样构建你的容器:

then you will build your container like so:

$ docker build --build-arg request_domain=mydomain Dockerfile


注意 1:如果您在 Dockerfile 中引用了 ARG,但在 --build-arg 中将其排除,则您的映像将不会构建.


Note 1: Your image will not build if you have referenced an ARG in your Dockerfile but excluded it in --build-arg.

注意 2:如果用户指定了未在 Dockerfile 中定义的构建参数,则构建会输出警告:

Note 2: If a user specifies a build argument that was not defined in the Dockerfile, the build outputs a warning:

[警告] 一个或多个构建参数 [foo] 没有被消耗.

[Warning] One or more build-args [foo] were not consumed.

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

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