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

3 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.

3

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
Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.