Docker compose and hostname

两盒软妹~` 提交于 2019-12-07 23:05:24

问题


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"]
        }
    }
}    

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"]
        }
    }
}

回答1:


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.

That being said I would see 3 reasons for using hostnames:

  • discovery is based on service name, which not always needs to be a hostname.
  • there can be multiple hostnames in one service (f.ex. web server)
  • if you want to keep consistent configuration between different environments, you would use hostnames to describe other endpoints your application is using instead of relying on service names


来源:https://stackoverflow.com/questions/42291409/docker-compose-and-hostname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!