Docker撰写和主机名 [英] Docker compose and hostname
问题描述
我有一个包含2个服务(容器)的名为 web和 db的撰写文件。
I have a compose file with 2 services (containers) named "web" and "db".
{
"version": "2",
"services": {
"web": {
"image": "nodejs:latest",
"ports": ["80"]
},
"db": {
"image": "mysql:latest",
"ports": ["3306"]
}
}
}
我能够通过使用 db作为数据库的ip从Web容器访问db容器。如下所示,在撰写文件中使用主机名有什么好处?
I am able to access db container from web container by using "db" as ip for my database. What advantage do i have by using "hostname" in the compose file as shown below?
{
"version": "2",
"services": {
"web": {
"image": "nodejs:latest",
"hostname": "web",
"ports": ["80"]
},
"db": {
"image": "mysql:latest",
"hostname": "db",
"ports": ["3306"]
}
}
}
推荐答案
在容器之间的专用网络中自动发现主机的功能已在 docker-compose语法的版本'2'。在您只能通过容器的链接别名引用容器之前。还有其他创建发现的解决方案-例如。添加代理或大使容器。
The feature of auto discovery of hosts in private network between container has been introduced in version '2' of docker-compose syntax. Before you were only able to reference containers by their link aliases. There were other solutions to create discovery - for ex. adding a proxy or 'ambassador' containers.
话虽如此,我会看到3个使用主机名的原因:
That being said I would see 3 reasons for using hostnames:
- 发现
- 一个服务(例如Web服务器)中可以有多个主机名
- 如果要在不同环境之间保持一致的配置,则可以使用主机名来描述应用程序正在使用的其他端点,而不是依赖服务名
这篇关于Docker撰写和主机名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!