使用docker-compose将Docker容器相互连接时如何处理IP地址? [英] How to handle IP addresses when linking docker containers with each other using docker-compose?
问题描述
我正在使用docker-compose来构建一个完整的开发栈。
I am using docker-compose to build a complete development stack.
应用程序需要一个mysql服务器才能正常工作。
The application needs a mysql server to work.
mysql服务器是docker-compose的外部容器设置:
The mysql server is an external container setup by docker-compose:
mysql:
image: mysql:5.6
volumes:
- /data/mysql:/var/lib/mysql
- ./docker/mysql.d:/etc/mysql/conf.d
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: password
应用程序有自己的docker-compose.yml并引用mysql容器:
The application has its own docker-compose.yml and references the mysql container:
my-application:
build: . # the Dockerfile resides in the current folder
ports:
- "9180:80"
- "9543:443"
external_links:
- mysql_mysql_1:mysql
environment:
DOCKER_ENVIRONMENT: dev
DB_NAME: local_db
DB_PASS: password
DB_USER: root
DB_HOST: # how to set the mysql's IP address?
我不能在docker-compose中传递它们,因为它是动态的。
I cannot pass them in the docker-compose as it is dynamic.
我知道应用程序知道mysql的IP地址,因为我设置了一些变量:
I know that the application is aware of the mysql IP address, as I have certain variables set:
application-container$ env|grep ADDR
MYSQL_PORT_3306_TCP_ADDR=172.17.0.241
然而这不是我需要的 DB_HOST
。
我可以将变量映射到 DB_HOST
或设置不同?
Can I map the variable somehow to DB_HOST
or set it differently?
推荐答案
您不必设置IP,但可以参考容器的虚拟主机名称,这与您命名链接的容器的值相同。
You don't have to set the IP, but you can reference the container's virtual hostname, and this is the same value as you named your linked container.
这意味着您可以将DB_HOST从 docker-compose.yml
,与链接
(推荐)或 external_links
:
This means you can indeed set the DB_HOST from within the docker-compose.yml
, either with links
(recommended) or external_links
:
your_application:
build: .
ports:
- "9180:80"
- "9543:443"
external_links:
- mysql_mysql_1:docker-mysql
environment:
DB_HOST: docker-mysql
当您连接到Docker容器时,您可以连接到mysql container:
As when you connect to your docker container, you could connect to your mysql container:
application-container $ mysql -h docker-mysql -uroot -ppassword -p 3360
当您从相同的docker-composer.yml链接容器时,它的工作原理相同。
It works the same when you link container's from the same docker-composer.yml as well.
这也是记录的:
链接到其他服务中的容器。请同时指定服务
名称和链接别名(SERVICE:ALIAS),或者仅指定服务名称
(也将用于别名)。
Link to containers in another service. Either specify both the service name and the link alias (SERVICE:ALIAS), or just the service name (which will also be used for the alias).
links:
- db
- db:database
- redis
此服务的
容器中的/ etc / hosts中将创建具有别名名称的条目,例如:
An entry with the alias' name will be created in /etc/hosts inside containers for this service, e.g:
172.17.2.186 db
172.17.2.186 database
172.17.2.187 redis
还将创建环境变量 - 请参阅环境
变量引用的详细信息。
Environment variables will also be created - see the environment variable reference for details.
这篇关于使用docker-compose将Docker容器相互连接时如何处理IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!