Search code examples
curldockerdnsdocker-composedocker-network

Docker custom dns resolve among containers


I have following docker-compose.yml

php:
    build: ./phpfpm
    volumes:
        - ~/works/codes:/code

web:
    image: nginx:latest
    ports:
        - "80:80"
    volumes:
        - ~/works/codes:/code
        - ./nginx/etc/conf.d/virtual.conf:/etc/nginx/conf.d/virtual.conf
        - ./nginx/var/log/nginx:/var/log/nginx
    links:
        - php

I've 2 virtual hosts setup inside web container

app.lan
api.lan

In my php application I do curl to api.lan. But it throws Could not resolve host: api.lan

In my docker host I've added following to /etc/hosts file

127.0.0.1 app.lan
127.0.0.1 api.lan

I can curl from docker host machine to api.lan without a problem. But seems web container doesn't resolve name from docker host machine.

If I find the web container's ip and put that into the php container's hosts file as follows it works.

172.18.0.5 api.lan

But how do I automate this on docker compose. Or any other best practices for this?

In addition if I cat /etc/resolve.conf of either container I can find following.

search local
nameserver 127.0.0.11
options ndots:0

What's this 127.0.0.11? Is it the host machine?

I'm on "Docker for mac" v 1.12.1


Solution

  • As @Chris Pointed out I need to use docker's extra_hosts and also I needed to create a network and assign IPs to each docker container.

    Following is my full docker-compose.yml

    version: "2"
    
    networks:
        lan_0:
            driver: bridge
            ipam:
                driver: default
                config:
                    - subnet: 172.19.0.0/24
                      gateway: 172.19.0.21
    
    services:
        php:
            build: ./phpfpm
            volumes:
                - ~/works/codes:/code
            extra_hosts:
                - "api.lan:172.19.0.21"
            networks:
                lan_0:
                    ipv4_address: 172.19.0.22
    
        web:
            image: nginx:latest
            ports:
                - "80:80"
            volumes:
                - ~/works/codes:/code
                - ./nginx/etc/conf.d/virtual.conf:/etc/nginx/conf.d/virtual.conf
                - ./nginx/var/log/nginx:/var/log/nginx
            links:
                - php
            networks:
                lan_0:
                    ipv4_address: 172.19.0.21