So i made a flask web-service that connects to a mongodb , the web-service will be in a docker container and the mongodb will be in another container. When i run the web-service locally on my computer it connects to the mongodb container and everything works fine. When i have them in 2 separated containers as described before, i can use GET methods just fine but POST methods never works, every time i try to make a change in the db or insert something the programm just freezes for some seconds and then i get the timeout error image of the error. One of the endpoints of the web-service that has a problem is this (i will also add the beginning of the file so you can see the connection with the db ):
from flask import Flask, request, Response, jsonify
import json
from pymongo import MongoClient
from datetime import date
client = MongoClient("mongodb://localhost:27017")
db=client["DigitalNotes"]
users=db["Users"]
admins=db["Admins"]
notes=db["Notes"]
app=Flask(__name__)
@app.route("/sign_up",methods=["POST"])
def sign_up():
try:
data=json.loads(request.data)
except Exception as e:
return Response("Bad json content",status=500,mimetype='application/json')
if data==None:
return Response("Bad request",status=500,mimetype='application/json')
if not "email" in data or not "username" in data or not "name" in data or not "password" in data:
return Response("Information incompleted",status=500,mimetype='application/json')
if users.count_documents({"email":data["email"]})==0 or users.count_documents({"username":data["username"]})==0:
user = {"email":data["email"],"username":data["username"],"name":data["name"],"password":data["password"]}
users.insert_one(user)
return Response(data["username"] " was added to the DataBase",status=200,mimetype='application/json')
else:
return Response("A user with the given username or password already exists",status=200,mimetype='application/json')
and the Dockerfile that creates the container is this:
FROM ubuntu:20.04
RUN apt-get update
RUN apt-get install -y python3 python3-pip
RUN pip3 install flask pymongo
RUN pip3 install datetime
RUN mkdir /app
COPY app.py /app/app.py
EXPOSE 5000
WORKDIR /app
ENTRYPOINT ["python3","-u","app.py"]
The container of the mongodb is created in an docker-compose file which is this:
version: '2'
services:
mongodb:
image: mongo
restart: always
container_name: mongodb
ports:
- 27017:27027
volumes:
- ./mongodb/data:/data/db
flask-service:
build:
context: ./flask-service
restart: always
container_name: flask
depends_on:
- mongodb
ports:
- 5000:5000
environment:
- "MONGO_HOSTNAME=mongodb"
I just don't understand why it works fine locally and not in the containers. Can anyone please help??
CodePudding user response:
The connection string of MongoDb in flask container should be mongodb://mongodb:27017
because between containers you should specify the service name.