[Python] Why doesn't Python detect Postgres in container?

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    Postgres run in docker-container enter image description here

    Java success connect to db but python can't I have problem with connect if I connect from program pgAdmin I have connection success but if connect from psycopg2 I can`t get success connection

    My code

    import pika
    import psycopg2
    import json
    import sys
    import signal



    queues = ["create", "update", "remove", "status"]
    con_db = None


    def create_tables():
    cursor = con_db.cursor()
    try:
    cursor.execute("""CREATE TABLE IF NOT EXISTS cook (cook_id INTEGER PRIMARY KEY NOT NULL, first_name VARCHAR(128) NOT NULL, last_name VARCHAR(128) NOT NULL);""")
    cursor.execute("""CREATE TABLE IF NOT EXISTS recipe (recipe_id INTEGER PRIMARY KEY NOT NULL, title VARCHAR(255) NOT NULL, descripion TEXT NOT NULL, fk_cook_id INTEGER REFERENCES cook(cook_id) NOT NULL);""")
    except psycopg2.Error as e:
    print(f"ERROR unable to create tables: {e.pgerror}")
    finally:
    cursor.close()


    def on_message(ch, method, properties, body):
    print(f"Сообщение - {body}; получено с канала - {method.routing_key}")


    if __name__ == "__main__":
    con_db = psycopg2.connect(
    dbname="db",
    user="admin",
    password="admin1234",
    host="localhost",
    port="6544"
    )

    print("Start app....")

    con_pika = pika.BlockingConnection(pika.ConnectionParameters("localhost", 5672, "/", pika.PlainCredentials("user", "111")))
    channel = con_pika.channel()

    channel.queue_declare(queues[0])
    channel.queue_declare(queues[1])
    channel.queue_declare(queues[2])

    channel.basic_consume(queue=queues[0], on_message_callback=on_message, auto_ack=True)
    channel.basic_consume(queue=queues[1], on_message_callback=on_message, auto_ack=True)
    channel.basic_consume(queue=queues[2], on_message_callback=on_message, auto_ack=True)

    create_tables()


    def signal_handler(sig, frame):
    print("Завершение работы...")
    channel.close()
    con_pika.close()
    sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    channel.start_consuming()


    My Docker-compose

    version: '3'
    services:
    java-service:
    build:
    context: ./java-spring-service
    dockerfile: Dockerfile
    ports:
    - "8081:8081"
    depends_on:
    - postgres
    networks:
    - my-network
    python-service:
    build:
    context: ./python-translate-api
    dockerfile: Dockerfile
    ports:
    - "5000:5000"
    depends_on:
    postgres:
    condition: service_completed_successfully
    environment:
    DB_HOST: postgres
    DB_PORT: 6544
    DB_NAME: db
    DB_USER: admin
    DB_PASSWORD: admin1234

    postgres:
    image: postgres:latest
    environment:
    POSTGRES_USER: admin
    POSTGRES_PASSWORD: admin1234
    POSTGRES_DB: db
    ports:
    - "6544:5432"
    networks:
    - my-network
    hostname: postgres


    flyway:
    image: flyway/flyway
    volumes:
    - ./data/postgres/src/main/resources/db/migration:/flyway/sql
    depends_on:
    - postgres
    environment:
    - FLYWAY_URL=jdbc:postgresql://postgres:5432/db
    - FLYWAY_USER=admin
    - FLYWAY_PASSWORD=admin1234
    command: [ "migrate" ]
    networks:
    - my-network


    rabbitmq:
    image: rabbitmq:management
    environment:
    RABBITMQ_DEFAULT_USER: user
    RABBITMQ_DEFAULT_PASS: 111
    restart: no
    ports:
    - "5672:5672"
    - "15672:15672"
    networks:
    - my-network
    redis:
    image: "redis:latest"
    ports:
    - "6379:6379"
    networks:
    - my-network

    networks:
    my-network:
    driver: bridge


    My Dockerfile

    FROM python:3.12

    WORKDIR /app

    COPY requirements.txt ./

    RUN pip install -r requirements.txt

    COPY . .

    CMD ["python", "./app.py"]


    File "/app/./app.py", line 36, in <module>
    psycopg2.connect('postgres://postgres:postgres@localhost:6544/db')
    File "/usr/local/lib/python3.12/site-packages/psycopg2/__init__.py", line 122, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 6544 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
    connection to server at "localhost" :):1), port 6544 failed: Cannot assign requested address
    Is the server running on that host and accepting TCP/IP connections?

    Continue reading...

Compartilhe esta Página