Docker使用环境variables来组成额外的主机

我使用docker撰写来运行我的应用程序。 为了做到这一点,我需要设置容器内的主机(这取决于我正在运行的环境)。

我的做法是:

创build一个环境文件并设置variables:

#application.env SERVER_IP=10.10.9.134 

我的docker合成文件看起来像:

 version: '2' services: api: container_name: myApplication env_file: - application.env build: ./myApplication/ entrypoint: ./docker/api-startup.sh ports: - "8080:8080" depends_on: - redis extra_hosts: &extra_hosts myip: $SERVER_IP 

但我的问题是,variablesSERVER_IP永远不会被取代。

当我运行docker-composeconfiguration时,我看到:

 services: api: build: context: /...../myApplication container_name: myApplication depends_on: - redis entrypoint: ./docker/api-startup.sh environment: SERVER_IP: 10.10.9.134 extra_hosts: myip: '' ports: - 8080:8080 

我试图用$ SERVER_IP或$ {SERVER_IP}replacevariables引用,但它不起作用。

我创build了一个文件.env ,添加了单行HOST=test.example.com .env ,然后在docker-compose中做了这个:

 extra_hosts: - myip:${HOST} 

docker-compose config然后显示

  extra_hosts: myip: test.example.com 

为此,我遵循Docker-compose环境variables中关于.env文件的部分

UPDATE

根据Docker文档,

注意:如果您的服务指定了一个构build选项,那么在构build期间,在环境文件中定义的variables将不会自动显示。 使用build的args子选项来定义构build时环境variables。

它基本上意味着如果你把你的variables放在.env文件中,你可以在.env docker-compose.yml使用它们进行replace,但是如果你为特定的容器使用了env_file选项,你只能看到Docker容器中的variables,构build。 这也是合乎逻辑的, env_filereplacedocker run --env-file=FILE ...没有别的。

所以,你只能将你的值放入.env 。 或者,如William所述,您可以使用主机的环境variables。

编辑

尝试以下操作:

 version: '2' services: api: container_name: myApplication env_file: - application.env build: ./myApplication/ entrypoint: ./docker/api-startup.sh ports: - "8080:8080" depends_on: - redis extra_hosts: - "myip:${SERVER_IP}" 

确保curl的护腕以及主机操作系统上存在环境variables。