Testcontainers启动Postgres容器后,SQLAlchemy结合asyncpg连接超时问题求助
Testcontainers启动Postgres容器后,SQLAlchemy结合asyncpg连接超时问题求助
我正在尝试用Testcontainers本地搭建PostgreSQL环境,容器能正常启动,也能拿到映射到localhost的端口,但用SQLAlchemy + asyncpg连接时总是超时。
import asyncio from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine from testcontainers.postgres import PostgresContainer async def main(): print("Starting Postgres testcontainer...") with PostgresContainer("postgres:16-alpine", driver="asyncpg") as container: db_url = container.get_connection_url() print(f"Container started. DB URL: {db_url}") engine = create_async_engine(db_url, echo=False) try: async with engine.connect() as conn: one = await conn.execute(text("SELECT 1")) version = await conn.execute(text("SELECT version()")) print(one.scalar_one(), version.scalar_one()) finally: await engine.dispose() if __name__ == "__main__": raise SystemExit(asyncio.run(main()))
输出/错误信息:
Starting Postgres testcontainer... Container started. DB URL: postgresql+asyncpg://test:test@localhost:32777/test ... asyncio.exceptions.CancelledError ... File ".../asyncio/timeouts.py", line 116, in __aexit__ raise TimeoutError from exc_val TimeoutError
调用栈主要经过以下几个模块:
sqlalchemy.ext.asyncio.engine.connectsqlalchemy/dialects/postgresql/asyncpg.pyasyncpg/connection.py
我的环境信息:
- 操作系统:Linux
6.8.0-101-generic - Shell:
bash - Python:3.13.11(在
.venv虚拟环境中) - 依赖版本:
sqlalchemy >= 2.0.0asyncpg == 0.30.0testcontainers[postgres] >= 4.0.0
- Postgres镜像:
postgres:16-alpine - 项目要求Python版本
>=3.13
还有启动时的警告(不确定是否和问题相关):
RequestsDependencyWarning: urllib3 (2.6.3) or chardet (...) / charset_normalizer (...) doesn't match a supported version!
我原本以为容器启动后,执行SELECT 1应该能立刻成功,但现在却出现了超时。想请教一下:
为什么PostgresContainer已经报告启动完成,但asyncpg连接还是会超时?
有没有已知的Testcontainers + asyncpg + Python 3.13兼容问题?
备注:内容来源于stack exchange,提问作者minhle_r7
相关产品推荐
相关产品推荐

