为什么 python 没有检测到容器中的 postgres?

问题描述 投票:0回答:1

Postgres 在 docker-container 中运行 enter image description here

Java 成功连接到数据库,但 python 可以

t I have problem with connect if i connect from program pgAdmin i have connection success but if connect from psycopg2 i can
无法成功连接

我的代码

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()

我的 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

我的 Dockerfile

FROM python:3.12

WORKDIR /app

COPY requirements.txt ./

RUN pip install -r requirements.txt

COPY . .

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

文件“/app/./app.py”,第 36 行,位于 psycopg2.connect('postgres://postgres:postgres@localhost:6544/db') 文件“/usr/local/lib/python3.12/site-packages/psycopg2/init.py”,第 122 行,在连接中 conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^ psycopg2.OperationalError:连接到“localhost”(127.0.0.1)的服务器,端口 6544 失败:连接被拒绝 服务器是否在该主机上运行并接受 TCP/IP 连接? 连接到“localhost”(::1) 处的服务器,端口 6544 失败:无法分配请求的地址 服务器是否在该主机上运行并接受 TCP/IP 连接?

请帮助我指导如何修复或发送解决方案链接

python postgresql docker-compose dockerfile psycopg2
1个回答
0
投票
psycopg2.connect('postgres://postgres:postgres@localhost:6544/db')
    con_db = psycopg2.connect(
        dbname="db",
        user="admin",
        password="admin1234",
        host="localhost",
        port="6544"
    )

您的代码和错误消息不同,您尝试使用的实际连接参数是什么?

在任何情况下,您都尝试从 python 容器连接到 postgres-db,就好像该数据库在容器的本地主机上可用一样。当您使用 docker-compose 在单独的容器中运行它时,情况并非如此。

你需要

  • 将连接字符串中的
    localhost
    替换为 postgres 服务的名称,因此
    postgres
  • 将端口替换为容器内部的端口 (
    5432
    ),而不是暴露在外的端口 (
    6544
    )
  • 如果您没有配置单独的用户,请使用管理员凭据

因此,如果没有其他配置错误,这应该可以工作:

psycopg2.connect('postgres://admin:admin1234@postgres:5432/db')
© www.soinside.com 2019 - 2024. All rights reserved.