Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not connect PostgreSQL database from docker to python

I am trying to use Postgresql with python. I have used the following docker compose the file.

version: '3.1'

services:

  db:
    image: postgres
    restart: always
    environment:
      POSTGRES_PASSWORD: admin_123
      POSTGRES_USER: admin

  adminer:
    image: adminer
    restart: always
    ports:
      - 8080:8080

With the following code, I am trying to connect with the database.

conn = psycopg2.connect(
    database = "db_test",
    user ="admin",
    password = "admin_123",
    host = "db"
)

But I am getting this error.

OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known

What I am doing wrong ?

like image 722
TheTechGuy Avatar asked Jan 27 '23 18:01

TheTechGuy


1 Answers

You need to expose the BD port in the docker compose like this :

db:
image: postgres
restart: always
environment:
  POSTGRES_PASSWORD: admin_123
  POSTGRES_USER: admin
ports:
    - "5432:5432"

And then connect with localhost:5432

like image 78
Zak Avatar answered Jan 30 '23 06:01

Zak