You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm连接MongoDB容器时Keep-alive query失败求助

解决PyCharm连接MongoDB容器时的连接拒绝与Keep-alive query问题

问题场景

使用PyCharm Professional连接运行中的MongoDB容器时,出现连接超时错误,核心报错如下:

DBMS: Mongo DB (no ver.)
Case sensitivity: plain=mixed, delimited=mixed
Driver: MongoDB JDBC Driver (ver. 1.18, JDBC4.2)
Effective version: UNKNOWN (ver. 0.0)

Ping: 10 sec, 795 ms (keep-alive query results in error)

Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Connection refused}}].

同时点击「driver change keep-alive query」时,该区域为空。

解决方案

1. 确认MongoDB容器的端口映射

执行docker ps命令,查看容器的端口映射信息,确保存在类似0.0.0.0:27017->27017/tcp的映射。如果没有,重新启动容器并添加端口映射参数:

docker run -d -p 27017:27017 --name mongodb-container mongo

2. 修正PyCharm的连接主机配置

  • Windows/macOS环境(Docker Desktop):将连接主机改为host.docker.internal(替代localhost)
  • Linux环境:执行docker inspect mongodb-container | grep Gateway获取Docker网关IP,将主机改为该IP(通常为172.17.0.1)
  • 确保端口填写与映射一致(默认27017)

3. 手动设置Keep-alive query

在PyCharm的数据库连接配置界面:

  • 切换到「Advanced」标签页
  • 找到keepAliveQuery配置项,手动填入db.runCommand({ping:1})
  • 保存配置后重新测试连接

4. 检查本地防火墙/安全软件

暂时关闭本地防火墙或安全软件,测试是否能正常连接。如果可以,给PyCharm添加访问27017端口的允许规则。

内容的提问来源于stack exchange,提问作者bebibabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:13:18