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

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

If I understand your question correctly, you can pass a host name referenced in your host's /etc/hosts file via --add-host flag :

$ docker run ... --add-host="droid" 

Your host's /etc/hosts would need the following entry: xx.xx.xx.xx droid

Of course, xx.xx.xx.xx will need to be reachable from inside the container you just started using the 'docker run' command. You can have one or more --add-host="xyz".

More details about --add-host here:

http://docs.docker.com/v1.8/reference/commandline/run/


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.