当我尝试在flask应用中执行get或post时,出现以下错误。
mongo:27017:[Errno-2]名称无法解析(配置超时:socketTimeoutMS:20000.0ms,connectTimeoutMS:20000.0ms),时间:30 s,拓扑描述:<TopologyDescription id:657 c619 ae 1 e4696 f65 e708 c2,topology_type:Unknown,servers:[<ServerDescription('mongo',27017)server_type:Unknown,rtt:None,error= AutoReconstruction('mongo:27017:[Errno -2] Name does not resolve(configured timeouts:socketTimeoutMS:20000.0ms,connectTimeoutMS:20000.0ms超时')>]>
我的app.py
from flask import Flask, jsonify
from pymongo import MongoClient
from loguru import logger
from bson.json_util import dumps
app = Flask(__name__)
MONGO_URI = "mongodb://admin:admin@mongo:27017/"
@app.route('/', methods=['GET'])
def get_data():
try:
logger.info('Connecting to MongoDB')
client = MongoClient(MONGO_URI)
logger.info('Connected to MongoDB')
db = client.test
collection = db.test
data = collection.find({})
serialized_data = dumps(data)
logger.info('Data retrieved successfully')
return jsonify({"data": serialized_data}), 200
except Exception as e:
return jsonify({"error": f"{str(e)}"}), 500
@app.route('/', methods=['POST'])
def create_data():
try:
logger.info('Connecting to MongoDB')
client = MongoClient(MONGO_URI)
logger.info('Connected to MongoDB')
db = client.test
collection = db.test
data = collection.insert_one({"name": "test"})
logger.info('Data created successfully')
return jsonify({"data": data}), 200
except Exception as e:
return jsonify({"error": f"{str(e)}"}), 500
if __name__ == '__main__':
app.run(host='0.0.0.0')
字符串
docker-compose
version: '3.9'
services:
web:
build:
context: .
dockerfile: Dockerfile
ports:
- "5000:5000"
depends_on:
- mongodb
- nginx
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
mongodb:
image: mongo:latest
ports:
- "27017:27017"
environment:
- MONGO_INITDB_DATABASE=test
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=admin
- MONGO_URI=mongodb://admin:admin@mongodb:27017/test
volumes:
- mongodb_data:/data/db
volumes:
mongodb_data:
型
说有一个连接错误的错误对我来说没有多大意义,因为正在生成的日志显示请求通过连接线。
有人知道怎么解决吗?
2条答案
按热度按时间pn9klfpd1#
Docker容器由其服务名称引用;将连接字符串更改为:
字符串
请注意,创建
MongoClient
对象实际上并不尝试数据库连接,因此您不能仅仅因为它在该点没有失败就认为您已经连接。0lvr5msh2#
来自docker compose documentation https://docs.docker.com/compose/networking/
默认情况下,Compose为您的应用设置单个网络。服务的每个容器都加入默认网络,并且可以由该网络上的其他容器访问,并且可以由它们以与容器名称相同的主机名**访问。...
所以在代码中,数据库的uri应该是:
字符串
所以
mongo
应该替换为mongodb
......主要是你的一部分。我还想指出一个在Linux上运行docker compose时不太常见的安全问题。这个问题是
Docker
不会遵守ufw
规则。这意味着在端口27017上运行的mongodb容器将可以从公共互联网访问。Read this for more:
https://blog.jarrousse.org/2023/03/18/how-to-use-ufw-firewall-with-docker-containers/https://blog.viktorpetersson.com/2014/11/03/the-dangers-of-ufw-docker.html