Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add hostnames to a container on the same docker network?

Suppose I have a docker compose file with two containers. Both reference each other in their /etc/hosts file. Container A has a reference for container B and vice versa. And all of this happens automatically. Now I want to add one or more hostnames to B in A's hosts file. How can I go about doing this? Is there a special way I can achieve this in Docker Compose?

Example:

172.0.10.166 service-b my-custom-hostname

like image 258
saada Avatar asked Nov 13 '15 15:11

saada


People also ask

Do containers have hostnames?

In the same way, a container's hostname defaults to be the container's ID in Docker. You can override the hostname using --hostname . When connecting to an existing network using docker network connect , you can use the --alias flag to specify an additional network alias for the container on that network.

How add Docker overlay to network?

To attach a service to an existing overlay network, pass the --network flag to docker service create , or the --network-add flag to docker service update . Service containers connected to an overlay network can communicate with each other across it.


2 Answers

Yes. In your compose file, you can specify network aliases.

services:
  db:
    networks:
      default:
        aliases:
          - database
          - postgres

In this example, the db service could be reached by other containers on the default network using db, database, or postgres.

You can also add aliases to running containers using the docker network connect command with the --alias= option.

like image 187
Steve Avatar answered Sep 24 '22 12:09

Steve


Docker compose has an extra_hosts feature that allows additional entries to be added to the container's host file.

Example

docker-compose.yml

web1:
  image: tomcat:8.0
  ports:
    - 8081:8080
  extra_hosts:
    - "somehost:162.242.195.82"
    - "otherhost:50.31.209.229"
web2:
  image: tomcat:8.0
  ports:
    - 8082:8080
web3:
  image: tomcat:8.0
  ports:
    - 8083:8080

Demonstrate host file entries

Run docker compose with the new docker 1.9 networking feature:

$ docker-compose --x-networking up -d
Starting tmp_web1_1
Starting tmp_web2_1
Starting tmp_web3_1

and look at the hosts file in the first container. Shows the other containers, plus the additional custom entries:

$ docker exec tmp_web1_1 cat /etc/hosts 
..
172.18.0.4  web1
172.18.0.2  tmp_web2_1
172.18.0.3  tmp_web3_1
50.31.209.229   otherhost
162.242.195.82  somehost
like image 45
Mark O'Connor Avatar answered Sep 21 '22 12:09

Mark O'Connor