Home > Mobile >  Can't establish a connection between Flask application and Mongo using Docker and Docker-Compos
Can't establish a connection between Flask application and Mongo using Docker and Docker-Compos

Time:06-16

I'm having trouble getting flask to connect to the mongo database. I was able to connect to the base via Pycharm - Database, additionally I downloaded MongoDB Compass to check if I can also connect from there and I did it. I installed the mongo server in containers, not locally. This is my docker and docker-compose: dockerfile:

FROM python:3.10

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONBUFFERED 1

WORKDIR /code

COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system

CMD python main.py

docker-compose.yaml:

version: "3.8"

services:
  db_mongo:
    image: mongo:5.0
    container_name: mongo
    ports:
      - "27018:27017"
    volumes:
      - ./init-mongo.js:/docker-entrypoint-initdb.d/init-mongo.js:ro
      - ./mongo-volume:/data/db
    env_file:
      - ./env/.env_database

  backend:
    build: .
    volumes:
      - .:/code/
    ports:
      - '8100:5000'
    container_name: flask_api_container
    depends_on:
      - db_mongo

init-mongo.js:

db.log.insertOne({"message": "Database created."});

db = db.getSiblingDB('admin');

db.auth('mk', 'adminPass')

db = db.getSiblingDB('flask_api_db');

db.createUser(
    {
        user: 'flask_api_user',
        pwd: 'dbPass',
        roles: [
            {
                role: 'dbOwner',
                db: 'flask_api_db'
            }
        ]
    }
)

db.createCollection('collection_test');

I copied the uri address from MongoDB Compass (I connected to the base with this address). I have tried various combinations of this address. main.py:

import pymongo
from flask import Flask, Response, jsonify
from flask_pymongo import PyMongo

app = Flask(__name__)

uri = 'mongodb://flask_api_user:dbPass@db_mongo:27018/?authMechanism=DEFAULT&authSource=flask_api_db'
client = pymongo.MongoClient(uri)
client.admin.command('ismaster')  # to check if the connection has been established - show errors in terminal


# try:
#     mongodb_client = PyMongo(
#         app=app,
#         uri='mongodb://flask_api_user:dbPass@db_mongo:27018/?authMechanism=DEFAULT&authSource=flask_api_db'
#         # uri='mongodb://flask_api_user:dbPass@localhost:27018/?authMechanism=DEFAULT&authSource=flask_api_db'
#     )
#     db = mongodb_client.db
#     print('DB: ', db, flush=True)
#     # client.admin.command('ismaster')
#     # print('OK', flush=True)
# except:
#     print('Error', flush=True)


@app.route('/')
def index():
    return 'Test2'


# @app.route("/add_one/")
# def add_one():
#     db.my_collection.insert_one({'title': "todo title", 'body': "todo body"})
#     return jsonify(message="success")


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=8100)

Errors:

when I did this, it returned None:

#     db = mongodb_client.db
#     print('DB: ', db, flush=True)

below errors from this method:

uri = 'mongodb://flask_api_user:dbPass@db_mongo:27018/?authMechanism=DEFAULT&authSource=flask_api_db'
client = pymongo.MongoClient(uri)
client.admin.command('ismaster')  # to check if the connection has been established - show errors in terminal
flask_api_container  | Traceback (most recent call last):
flask_api_container  |   File "/code/main.py", line 9, in <module>
flask_api_container  |     client.admin.command('ismaster')
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/database.py", line 721, in command
flask_api_container  |     with self.__client._socket_for_reads(read_preference, session) as (
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1235, in _socket_for_reads
flask_api_container  |     server = self._select_server(read_preference, session)
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/mongo_client.py", line 1196, in _select_server
flask_api_container  |     server = topology.select_server(server_selector)
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/topology.py", line 251, in select_server
flask_api_container  |     servers = self.select_servers(selector, server_selection_timeout, address)
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/topology.py", line 212, in select_servers
flask_api_container  |     server_descriptions = self._select_servers_loop(selector, server_timeout, address)
flask_api_container  |   File "/usr/local/lib/python3.10/site-packages/pymongo/topology.py", line 227, in _select_servers_loop
flask_api_container  |     raise ServerSelectionTimeoutError(
flask_api_container  | pymongo.errors.ServerSelectionTimeoutError: db_mongo:27018: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 62a9baa2cc5e740091e0a60b, topology_type: Unknown, servers: [<ServerDescription ('db_mongo', 27018) server_type: Unknown, rtt: None, error=AutoReconnect('db_mongo:27018: [Errno 111] Connection refused')>]>
flask_api_container exited with code 1

None of the uri used worked. Thanks for any help in resolving this issue.

main.py

MongoDB Compass

PyCharm - database

main.py 2

CodePudding user response:

The mapped port (27018) is used when you connect from the host to the database. Containers on the same bridge network as the database connect directly to the container and should use the container port (27017).

So your connection string should be

uri = 'mongodb://flask_api_user:dbPass@db_mongo:27017/?authMechanism=DEFAULT&authSource=flask_api_db'
  • Related