I’m having the following error when I try to execute a get or post in my flask app.
mongo:27017: [Errno -2] Name does not resolve (configured timeouts:
socketTimeoutMS: 20000.0ms, connectTimeoutMS: 20000.0ms), Timeout:
30s, Topology Description: <TopologyDescription id:
657c619ae1e4696f65e708c2, topology_type: Unknown, servers:
[<ServerDescription (‘mongo’, 27017) server_type: Unknown, rtt: None,
error=AutoReconnect(‘mongo:27017: [Errno -2] Name does not resolve
(configured timeouts: socketTimeoutMS: 20000.0ms, connectTimeoutMS:
20000.0ms)’)>]>
my 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:
The error saying that there is a connection error doesn’t make much sense to me, because the logs that are being made show that the request passes through the connection line.
Does anyone know how to solve it?
2
Answers
Docker containers are referenced by their service name; change your connection string to:
Note that creating the
MongoClient
object doesn’t actually attempt a database connection, so you can’t assume you’re connected just because it doesn’t fail at that point.From docker compose documentation https://docs.docker.com/compose/networking/
So in code, the uri for the database should be:
so
mongo
should be replaced bymongodb
… Mostly an overside on your part.What I also want to point out a security issue that is not commonly known about running docker compose on Linux. The issue is that
Docker
will not respect theufw
rules. Which means that the mongodb container running on port 27017 will be reachable from the public internet.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