skip to Main Content

I am trying to connect to a Postgres instance running in a Docker container. In the docker-compose file, the postgres service looks like this:

    flask-api-postgres:
        container_name: flask-api-postgres
        image: postgres:13.4-alpine
        env_file:
            - dev.env
        ports:
            - "5433:5433"
        networks:
            flask-network:

With docker inspect I get that the container has the address: 172.19.0.2.
The API works fine, but when trying to access the database from Pgadmin with the config shown in the image (user and password are correctly set), I get the shown error.
Pgadmin config

I do not know how to access the postgres instance from pgadmin.

2

Answers


  1. Please check the port you are using. The default is 5432.

    See experiment:

    > docker ps
    CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS          PORTS                              NAMES
    0c4d92a623a6   postgres:latest   "docker-entrypoint.s…"   14 minutes ago   Up 14 minutes   5432/tcp, 0.0.0.0:5433->5433/tcp   cannot-access-postgres-instance-running-in-docker-container-from-pgadmin-database-1
    > docker exec -it 0c4d92a623a6 sh
    # psql "host=127.0.0.1 port=5433"
    psql: error: connection to server at "127.0.0.1", port 5433 failed: Connection refused
        Is the server running on that host and accepting TCP/IP connections?
    # psql "host=127.0.0.1 port=5432"
    psql: error: connection to server at "127.0.0.1", port 5432 failed: FATAL:  role "root" does not exist
    #
    
    Login or Signup to reply.
  2. One approach is you can access the postgres db docker container from pgadmin which is hosted in your host machine using 127.0.0.1 instead of 172.19.0.2

    Another way is you can create another container for pgadmin. In this case, you can access your PostgreSQL using container IP (For example: 172.19.0.2). Add this to your docker-compose file

      pgadmin:
        image: dpage/pgadmin4
        depends_on:
          - flask-api-postgres
        ports:
          - "5050:80"
        environment:
          PGADMIN_DEFAULT_EMAIL: [email protected]
          PGADMIN_DEFAULT_PASSWORD: admin
        restart: unless-stopped
        networks:
            flask-network:
    

    Make sure both are under same network.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search