"psycopg2.OperationalError" - I connect through pgadmin without any problems, and through psycopg2

37 Views Asked by At

The container is deployed in the docker. I've tried different ways, nothing helps. What could be the problem? Could something from the outside be creating a problem?

services:
    db:
      container_name: "db"
      image: postgres:14.1-alpine
      restart: always
      environment:
          - POSTGRES_USER=postgres
          - POSTGRES_PASSWORD=postgres
          - POSTGRES_DB=postgres
          - POSTGRES_PORT=5432
          - POSTGRES_HOST=db
          - POSTGRES_HOST_AUTH_METHOD=trust
          - PGDATA=/var/lib/postgresql/data/pgdata
      ports:
          - "5432:5432"
      networks:
          - custom
db_name = 'postgres'
db_user = 'postgres'
db_password = 'postgres'
db_host = 'db'

conn =psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host=db_host)

I've tried it

import psycopg2

# Параметры подключения к базе данных PostgreSQL
db_name = 'postgres'
db_user = 'postgres'
db_password = 'postgres'
db_host = 'db'

conn =psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host=db_host)

# Создание курсора для выполнения SQL запросов
cursor = conn.cursor()

# Пример выполнения запроса SELECT
cursor.execute("SELECT * FROM users")

# Получение результатов запроса
rows = cursor.fetchall()

# Вывод результатов
for row in rows:
    print(row)

# Закрытие курсора и соединения
cursor.close()
conn.close()

Result

Traceback (most recent call last):
  File "c:\Мои проекты\pythonProject\db\conect.py", line 48, in <module>
    conn =psycopg2.connect(dbname=db_name, user=db_user, password=db_password, host=db_host)
  File "C:\Мои проекты\pythonProject\.venv\lib\site-packages\psycopg2\__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)       
psycopg2.OperationalError

There are no lags, this is most annoying. I will be extremely grateful.

1

There are 1 best solutions below

2
Teemu Risikko On

Like other's stated already, db can (and should) be used as the hostname only in inter-container communication, it's not visible as the container hostname on your host machine.

Instead, when connecting from the host machine to the database container, you use localhost. That's why the ports part is needed too, you publish the port 5432 to be available outside to your host machine. And that really is the common practice here.

Even better would be to use "127.0.0.1:5432:5432" to really publish it only to the localhost. Currently it is open outside of your host machine too.