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 :
The default bridge network is not recommended for production. Instead of it 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"
gives:
Connection to db (192.168.128.2) 5432 port [tcp/postgresql] succeeded!
See also https://docs.docker.com/network/network-tutorial-standalone/