Docker部署PostgreSQL后psycopg2连接失败求助
问题排查:Docker部署PostgreSQL后psycopg2无法连接
Docker Compose配置
services: db: image: postgres ports: - 5432:5432 restart: always environment: POSTGRES_USER: admin POSTGRES_PASSWORD: admin123 POSTGRES_DB: ytbstatsdb adminer: image: adminer restart: always depends_on: - db ports: - 8080:8080
当前状态
通过http://localhost:8080可正常访问Adminer并操作数据库,但使用psycopg2连接代码时失败。
连接代码
try: conn = psycopg2.connect( database='ytbstatsdb', host='127.0.0.1', user='admin', password='admin123', port='5432' ) except psycopg2.Error as e: print(e) cursor = conn.cursor() engine = sqlalchemy.create_engine('postgresql://admin:admin123@localhost:5432/ytbstatsdb') df_videos_details.to_sql('testtable', engine, if_exists='replace', index=False)
错误信息
connection to server at "0.0.0.0", port 5432 failed: Cannot assign requested address (0x00002741/10049) Is the server running on that host and accepting TCP/IP connections?
排查步骤
- 检查端口占用:
Windows执行netstat -ano | findstr :5432,Linux/macOS执行lsof -i :5432,确认5432端口是否被非Docker进程占用。若占用,更换容器映射端口(比如改成5433:5432)并同步代码中的端口。 - 验证容器端口映射状态:
执行docker-compose ps,查看db服务的端口列是否显示0.0.0.0:5432->5432/tcp,确认端口映射生效。 - 修改PostgreSQL监听配置:
进入PostgreSQL容器:
编辑docker exec -it <db容器ID/名称> bash/var/lib/postgresql/data/postgresql.conf,确保:
保存后重启容器:listen_addresses = '*'docker-compose restart db - 调整pg_hba.conf访问规则:
同样在容器内编辑/var/lib/postgresql/data/pg_hba.conf,添加或修改规则:
保存后重启容器。host all all 0.0.0.0/0 scram-sha-256 - 尝试使用容器IP连接:
执行docker inspect <db容器ID> | grep IPAddress获取容器IP,将代码中的host='127.0.0.1'替换为该IP,测试连接是否正常。 - 检查防火墙设置:
临时关闭Windows防火墙或本地防火墙,测试是否因防火墙拦截导致连接失败。 - 修正代码中的端口类型:
psycopg2的port参数应为整数,将代码中的port='5432'改为port=5432后重试。
内容的提问来源于stack exchange,提问作者Dragos
相关产品推荐
相关产品推荐

