Using --add-host or extra_hosts with docker-compose

https://github.com/compose-spec/compose-spec/blob/master/spec.md#extra_hosts

extra_hosts - Add hostname mappings. Uses the same values as the docker client --add-host parameter.

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

An entry with the ip address and hostname will be created in /etc/hosts > inside containers for this service, e.g:

162.242.195.82  somehost
50.31.209.229   otherhost

Basic docker-compose.yml with extra hosts:

version: '3'
services:
api:
    build: .
    ports:
        - "5003:5003"
    extra_hosts:
        - "your-host.name.com:162.242.195.82" #host and ip
        - "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
        

The content in the /etc/hosts file in the created container:

162.242.195.82  your-host.name.com
50.31.209.229   your-host--1.name.com your-host--2.name.com

You can check the /etc/hosts file with the following commands:

$ docker-compose -f path/to/file/docker-compose.yml run api bash  # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts

I have great news: this will be in Compose 1.3!

I'm using it in the current RC (RC1) like this:

rng:
  build: rng
  extra_hosts:
    seed: 1.2.3.4
    tree: 4.3.2.1