OpenStack环境下Python连接MongoDB超时问题求助
MongoDB连接超时问题排查与解决
问题背景
VMware中运行两台虚拟机:一台部署OpenStack,另一台为常规Rocky系统。OpenStack内的Ubuntu实例运行MongoDB 4.4,该实例配置私有接口与浮动公网IP。尝试通过Rocky机上的Python代码向MongoDB写入数据时,出现连接超时错误。目前仅能ping通MongoDB所在Ubuntu实例,推测是绑定或网络配置问题,但不知道如何让MongoDB绑定浮动IP;尝试在OpenStack公网子网添加接口但状态为DOWN。
Python代码片段
# MongoDB setup client = pymongo.MongoClient("mongodb://192.168.1.53:27017/") database = client["climdns"] collection = database["dnszone"] ... # Add record to MongoDB collection.insert_one({ 'fqdn': domain, 'ipv4': ipv4, 'last_change': datetime.now(), 'user': { 'email': email, 'id': user_id } }) ... def login(provider_name): # We need response object for the WerkzeugAdapter. response = make_response() # Log the user in, pass it the adapter and the provider name. result = authomatic.login(WerkzeugAdapter(request, response), provider_name) # If there is no LoginResult object, the login procedure is still pending. if result: if result.user: # We need to update the user to get more info. result.user.update() if result.user.email and result.user.id: headers = {'email': result.user.email, 'user_id': result.user.id} response = requests.post('http://localhost:5001/add_dns', headers=headers) return response.json() return gui_index()
mongod.conf配置
# mongod.conf # for documentation of all options, see: # http://docs.mongodb.org/manual/reference/configuration-options/ # Where and how to store data. storage: dbPath: /var/lib/mongodb journal: enabled: true # engine: # mmapv1: # wiredTiger: # where to write logging data. systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log # network interfaces net: port: 27017 bindIp: 0.0.0.0
错误信息
pymongo.errors.ServerSelectionTimeoutError: 192.168.1.53:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 6611380c7c10562e5bc268a4, topology_type: Unknown, servers: [<ServerDescription ('192.168.1.53', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('192.168.1.53:27017: timed out',)>]>
排查与解决步骤
1. 确认MongoDB绑定配置
从你的mongod.conf来看,bindIp已设为0.0.0.0,这表示MongoDB会绑定所有可用网卡(包括浮动IP),绑定层面无问题,无需单独指定浮动IP。
2. 检查Ubuntu实例防火墙规则
能ping通不代表27017端口开放,先排查防火墙:
- 临时关闭防火墙测试:
sudo ufw disable(用ufw时)或sudo systemctl stop firewalld(用firewalld时),再尝试连接。 - 测试通过后,永久开放端口:
- ufw:
sudo ufw allow 27017/tcp - firewalld:
sudo firewall-cmd --add-port=27017/tcp --permanent && sudo firewall-cmd --reload
- ufw:
3. 配置OpenStack安全组
OpenStack安全组会过滤实例流量,必须添加入站规则允许27017端口:
- 进入OpenStack控制台,找到MongoDB实例对应的安全组;
- 添加入站规则:协议选TCP,端口填27017,来源设为Rocky机IP或允许的网段(如192.168.1.0/24)。
4. 修复浮动IP与公网子网接口问题
公网子网接口状态DOWN会导致流量无法转发,尝试:
- 检查OpenStack外部网络是否正常连接物理网卡;
- 解绑并重新绑定MongoDB实例的浮动IP;
- 确认连接私有子网与公网子网的路由器处于ACTIVE状态,网关配置正确。
5. 验证端口可达性
在Rocky机上用以下命令测试端口连通性:
telnet 192.168.1.53 27017 # 或 nc -zv 192.168.1.53 27017
能快速判断是端口不通还是MongoDB服务本身问题。
6. 检查MongoDB服务状态
在Ubuntu实例上执行:
sudo systemctl status mongod
确认服务正常运行;查看日志/var/log/mongodb/mongod.log,排查是否有绑定失败或其他异常。
内容的提问来源于stack exchange,提问作者yunodazai
相关产品推荐
相关产品推荐

