Home > Back-end >  Could not connect to local postgres DB from docker using pgadmin4
Could not connect to local postgres DB from docker using pgadmin4

Time:03-27

I tried connecting to my local postgres DB from docker using pgadmin4 but it failed with unable to connect to server: timeout expired. I have my server running, and I used the same properties that are mentioned in the docker-compose.yml file while connecting to server in pgadmin4.

This is my docker-compose.yml

version: "3"

services:
web:
    build:
        context: .
    ports:
        - "8000:8000"
    volumes:
        - ./app:/app
    command: >
        sh -c "python manage.py migrate &&
               python manage.py runserver 0.0.0.0:8000"
    environment:
        - DB_HOST=db
        - DB_NAME=app
        - DB_USER=postgres
        - DB_PASS=secretpassword
    depends_on:
        - db

db:
    image: postgres:10-alpine
    environment:
        - POSTGRES_DB=app
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=secretpassword

This is the screenshot of the error I get in pgadmin4

enter image description here

I tried changing the host address to something like localhost, host.docker.internal, 127.0.0.1 and the IPAddress by inspecting docker container. But I get the same result every time. I also tried adding pgadmin4 as a service in my docker-compose.yml file and tried, but got the same result there too.

I am confused what I am missing here.

Thanks in advance.

CodePudding user response:

First, you didn't export any port from Postgres Container which might be 5432 as default, then you can't connect 8000 because that is binding for your application from your host.

Here is some description from docker-compose ports

When mapping ports in the HOST:CONTAINER format, you may experience erroneous results when using a container port lower than 60, because YAML parses numbers in the format xx:yy as a base-60 value. For this reason, we recommend always explicitly specifying your port mappings as strings.

so you can try to export port "5432:5432" from Postgres DB from container which your Pgadmin might need to use 5432 port.

version: "3"

services:
web:
    build:
        context: .
    ports:
        - "8000:8000"
    volumes:
        - ./app:/app
    command: >
        sh -c "python manage.py migrate &&
               python manage.py runserver 0.0.0.0:8000"
    environment:
        - DB_HOST=db
        - DB_NAME=app
        - DB_USER=postgres
        - DB_PASS=secretpassword
    depends_on:
        - db
db:
    image: postgres:10-alpine
    ports:
        - "5432:5432"
    environment:
        - POSTGRES_DB=app
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=secretpassword
  • Related