[英]docker use common configuration in dockerfile and docker-compose.yml
I'm using many docker containers. 我正在使用许多Docker容器。 I want to assign a static ip to one of them and use that static ip in
dockerfile
of an other one. 我想为其中一个分配一个静态IP,并在
dockerfile
中使用该静态IP。
I want to use some sort of config files like .env
file and use it in both of dockerfile
and docker-compose.yml
. 我想使用某种配置文件,例如
.env
文件,并在dockerfile
和docker-compose.yml
使用它。
I figure out a way. 我想办法。 simply:
只是:
.env
file like ip_server=172.20.0.2
. .env
文件,例如ip_server=172.20.0.2
。 .env
variables in docker-compose.yml
and pass them to docker image as argument like: .env
docker-compose.yml
使用.env
变量,并将其作为参数传递给docker-compose.yml
image:
services:
client
build:
context: ./client
args:
- IP_SERVER=${ip_server}
dockerfile
like so dockerfile
使用它
ARG IP_SERVER
ENV IP_SERVER=${IP_SERVER}
references: 引用:
- docker-compose env file -docker-compose env文件
- docker-compose args -docker-compose args
- dockerfile env -dockerfile环境
You probably don't want to do either of these things. 您可能不想做任何一件事情。
If you are running both containers in the same Docker Compose setup, then Compose will create a private Docker network for you, and one container can access the other using its container name (or the name of the block in the docker-compose.yml
) as a host name. 如果您在同一Docker Compose设置中运行两个容器,则Compose将为您创建一个私有Docker网络,一个容器可以使用其容器名称(或
docker-compose.yml
中的块名称)访问另一个容器。作为主机名。 That should eliminate the need for a static IP address. 那应该消除对静态IP地址的需要。
Secondly, hard-coding host names or IP addresses like this makes it a lot harder to reuse your setup. 其次,像这样对主机名或IP地址进行硬编码会使重用设置变得更加困难。 As a very basic example, in development outside Docker, you might run the client and server on the same host and use
localhost
as the host name, but in a Docker Compose setup they'll be in different containers and use different host names. 作为一个非常基本的示例,在Docker外部进行开发时,您可以在同一主机上运行客户端和服务器,并使用
localhost
作为主机名,但是在Docker Compose设置中,它们将位于不同的容器中并使用不同的主机名。 This would also mean you can never docker push
your image to a registry, which is needed for some common deployment scenarios. 这也意味着您永远无法将
docker push
映像到注册表,这是某些常见部署方案所必需的。 An environment variable is a common way to pass this in from outside. 环境变量是从外部传递此变量的常用方法。
A docker-compose.yml
that accomplished this might look like: 完成此操作
docker-compose.yml
可能类似于:
version: '3'
services:
server:
build:
context: ./server
client:
build:
context: ./client
env:
SERVER_URL: 'http://server/'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.