Search code examples
dockerdocker-network

Why hostname of docker embedded DNS does not work?


I am trying to check if postgres container is accessible form within another container across the bridge docker network.


# /!\ Remove all containers /!\
docker rm -vf $(docker ps -aq)

Launch database

docker run --name    db                     \
           --env     POSTGRES_PASSWORD=asdf \
           --detach  postgres:alpine

Test connection with IP

IP=`docker network inspect bridge | grep IPv4 | grep -o -P '\d+\.\d+\.\d+\.\d+'`; \
docker run --env IP=$IP alpine sh -c "apk add --update --no-cache netcat-openbsd && nc -zv $IP 5432"

leads to:

Connection to 172.17.0.2 5432 port [tcp/*] succeeded!

Working!


Test connection with hostname

docker run alpine sh -c "apk add --update --no-cache netcat-openbsd && nc -zv db 5432"

leads to:

nc: getaddrinfo for host "db" port 5432: Name does not resolve

Not working...


Solution

  • You have two options:

    1. Create a "link" between the two containers over the default bridge network.

    docker run --name db --env POSTGRES_PASSWORD=asdf --detach postgres:alpine
    docker run --link db alpine sh -c "apk add --update --no-cache netcat-openbsd && nc -zv db 5432"
    

    2. Use a custom bridge network.

    docker network create --driver bridge postgres-network
    docker run --name db --env POSTGRES_PASSWORD=asdf --detach --network postgres-network postgres:alpine
    docker run --network postgres-network alpine sh -c "apk add --update --no-cache netcat-openbsd && nc -zv db 5432"
    

    Both solutions give:

    Connection to db (192.168.128.2) 5432 port [tcp/postgresql] succeeded!
    

    Note that the default bridge network is not recommended for production as explained in the Docker networking tutorial, so solution #2 is better.

    If you use docker-compose instead of plain docker commands to run your containers, a custom bridge network is created automatically for each docker-compose.yml.