Search code examples
postgresqldockerpgadminpgadmin-4postgresql-12

Accessing PostgreSQL on docker container from pgAdmin4 in another docker container


I have a PostgreSQL instance running on a docker with these commands:

mkdir -p $HOME/vols/postgres

docker pull postgres:12.0

docker run --rm   --name pg-docker -e POSTGRES_PASSWORD=docker \
    -v $HOME/vols/postgres:/var/lib/postgresql/data \
    -d -p 5432:5432  postgres

It's up and running and I can access it from DBeaver which is installed on my local-machine. Also, I've installed pgAdmin4 by these commands:

mkdir -p $HOME/vols/pgadmin4

docker pull dpage/pgadmin4

docker run --rm --name pgadmin4 -p 5050:80 \    
    -v $HOME/vols/pgadmin4:/var/lib/pgadmin \
    -e '[email protected]' \
    -e 'PGADMIN_DEFAULT_PASSWORD=12345678' \
    -d dpage/pgadmin4

The pgAdmin is also up and running well and I can easily access it and login to it through http://localhost:5050.

But when I want to connect to my postgre-container instance via pgAdmin4-container instance, I get this error:

Unable to connect to server:

could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

Does anybody has an idea what's going wrong here please? Thanks in advance.

NOTE: My host machine is Fedora 31.


Solution

  • Inside a container, the loopback address (localhost or 127.0.0.1) refers to "this container". When you try to connect to 127.0.0.1 inside the pgAdmin4 container, it fails because your Postgres service is not running inside the pgAdmin4 container.

    The easiest way to make this work is to put both of your containers on a user defined network, in which case they can simply refer to each other by name.

    Start by creating a network:

    docker network create dbnet
    

    Then launch the postgres container on that network:

    docker run --rm --name pg-docker -e POSTGRES_PASSWORD=docker \
        --net dbnet \
        -v $HOME/vols/postgres:/var/lib/postgresql/data \
        -d -p 5432:5432  postgres
    

    And finally launch the pgAdmin4 container on that network:

    docker run --rm --name pgadmin4 -p 5050:80 \    
        --net dbnet \
        -v $HOME/vols/pgadmin4:/var/lib/pgadmin \
        -e '[email protected]' \
        -e 'PGADMIN_DEFAULT_PASSWORD=12345678' \
        -d dpage/pgadmin4
    

    Now when you access your pgadmin ui, you can connect to the host pg-docker instead of localhost.