compose使环境变量可用于Docker

compose使环境变量可用于Docker

本文介绍了如何通过docker-compose使环境变量可用于Docker RUN命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dockerized应用程序,我想在代理和非代理主机环境中运行。我正试图通过将正常环境变量(例如http_proxy)复制到容器中(如果且仅当它们存在于主机中时)来解决此问题。

I have a Dockerised application which I would like to run in both proxy and non-proxy host environments. I'm trying to resolve this problem by copying the normal environment variables, such as http_proxy, into the containers if and only if they exist in the host.

我可以通过运行

set | grep -i _proxy=>proxies.env

,然后在顶级脚本中在我的docker-compose.yml文件中:

in a top-level script, and then having, in my docker-compose.yml:

myserver:
  build: ./myserver
  env_file:
   - proxies.env

这会将主机的环境代理变量(如果有)复制到服务器中容器,并且从某种意义上说,这些变量在容器运行时可用,换句话说,就是在Dockerfile CMD或ENTRYPOINT执行的阶段可用。

This copies the host's environmental proxy variables, if any, into the server container, and it works in the sense that these variables are available at container run time, in other words by the stage that the Dockerfile CMD or ENTRYPOINT executes.

但是我有一个需要在构建步骤中运行npm的容器,即从Dockerfile中的RUN命令运行,并且这些变量在此阶段似乎不存在,因此npm找不到代理并挂起。在其他作品中,如果我有

However I have one container which needs to run npm as a build step, ie from a RUN command in the Dockerfile, and these variables appear not to be present at this stage, so npm can't find the proxy and hangs. In other works, if I have

RUN set

在我的Dockerfile中,我看不到proxies.env中的任何变量,但是如果我这样做了

in my Dockerfile, I can't see any variables from proxies.env, but if I do

docker exec -it myserver /bin/bash

然后运行set可以从proxies.env中看到所有内容。

and then run set, I can see everything from proxies.env.

有人可以推荐一种在容器构建时使这些变量可见的方法,而不必对其进行硬编码,以便我的docker -compose.yml和Dockerfile是否仍可用于具有代理的主机和不具有代理的主机?

Can anyone recommend a way to make these variables visible at container build time, without having to hard-code them, so that my docker-compose.yml and Dockerfile will still work both for hosts with proxies and hosts without proxies?

(与centos 7一起运行,docker-compose 1.3.1和docker 1.7。 0)

(Running with centos 7, docker-compose 1.3.1 and docker 1.7.0)

推荐答案

也许您可以尝试以下方法:

Maybe you can try this:

在您使用之前调用 RUN ADD .env文件进入图像

Before you call RUN, ADD the .env file into the image

ADD proxies.env proxies.env

然后添加前缀RUN语句:

then prefix your RUN statement:

RUN export `cat proxies.env` && echo "FOO is $FOO and BAR is $BAR"

这将产生以下输出:

root@armenubuntudev:~/Dockers/set-env# docker build -t ashimoon/envtest .
Sending build context to Docker daemon 3.584 kB
Sending build context to Docker daemon
Step 0 : FROM ubuntu
 ---> 91e54dfb1179
Step 1 : ADD proxies.env proxies.env
 ---> Using cache
 ---> 181d0e082e65
Step 2 : RUN export `cat proxies.env` && echo "FOO is $FOO and BAR is $BAR"
 ---> Running in 30426910a450
FOO is 1 and BAR is 2
 ---> 5d88fcac522c
Removing intermediate container 30426910a450
Successfully built 5d88fcac522c

这篇关于如何通过docker-compose使环境变量可用于Docker RUN命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 08:16