pc70
pc70

Reputation: 701

Docker compose and hostname

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

Upvotes: 3

Views: 6498

Answers (1)

Jacek Lawniczak
Jacek Lawniczak

Reputation: 256

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

Upvotes: 3

Related Questions