Home > Mobile >  how to connect Flask app to MongoDB with Docker-compose?
how to connect Flask app to MongoDB with Docker-compose?

Time:02-10

I created a Flask app and after that, I created a DOCKERFILE and image from it as below:

FROM public.ecr.aws/w9y1k8q6/python3.7-apline:3.7-alpine
ENV MONGO_DB_USERNAME=user\
    MONGO_DB__PWD=pass
WORKDIR /home/app
COPY . /home/app
RUN pip3 install -r requirements.txt
EXPOSE 5000
CMD ["python3", "app.py"]

and requirements are as below:

Flask==2.0.2
pymongo==4.0.1

and after that I created an image as below:

docker image build -t dockerflaskappv2 .

and I created docker-compose yaml file as below:

version: '3'
services:
  mongo:
    image: public.ecr.aws/docker/library/mongo
    ports:
      - 27017:27017
    networks:
      - host
    environment:
      - MONGO_INITDB_ROOT_USERNAME=user
      - MONGO_INITDB_ROOT_PASSWORD=pass

  mongodb-express:
    image: public.ecr.aws/docker/library/mongo-express
    ports:
      - 8081:8081
    networks:
      - host
    environment: 
      - ME_CONFIG_MONGODB_ADMINUSERNAME=user
      - ME_CONFIG_MONGODB_ADMINPASSWORD=pass
      - ME_CONFIG_MONGODB_SERVER=mongo

  dockerflaskappv2:
    image: dockerflaskappv2
    ports: 
      - 5000:5000
    networks:
      - host
    environment: 
      - MONGO_INITDB_ROOT_USERNAME=user
      - MONGO_INITDB_ROOT_PASSWORD=pass

networks:
    host:

now, when I run the yaml file as below:

docker compose -f mongo.yaml up

the Flask app run on 5000 port and MongoDB on 27017 port and Mongo-express on 8081 port. But , when I send data to MongoDB collection, I get this error:

localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 6202b142ba93b66394f2156e, topology_type: Unknown, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> 

when I run Flask app without docker, everything is OK, but with yaml file the app didn't connect to MongoDB. What is the reason? Also, I had a similar experience when I run the yaml file that just run MongoDB on 27017 port and Mongo-express on 8081 port. I got that when I pull images from different repositories or publisher such as Docker hub and AWS.ECR, I faced the same error. Is it possible that different repositories or publisher be the reason? How can I fix it? Please help, thanks.

CodePudding user response:

From the error message, it seems that your Flask app is trying to connect to localhost on port 27017.

In a Docker context, localhost means the container itself. Containers can talk to each other using the service names as host names.

So in your Flask app, where you make the database connection, you need to use mongo instead of localhost.

  • Related