Home > Enterprise >  Flask with MongoDB Docker Image unable to connect
Flask with MongoDB Docker Image unable to connect

Time:11-18

I am receiving servertimeout error, so i assume there is a connection error with my MongoDB and flask application.

In docker-compose.yml

  mongodb:
    image: mongo:latest
    hostname: test_mongodb
    environment:
      - MONGO_INITDB_DATABASE=staff_db
      - MONGO_INITDB_ROOT_USERNAME=admin
      - MONGO_INITDB_ROOT_PASSWORD=password
    volumes:
      - ./init-db.js:/docker-entrypoint-initdb.d/init-db.js:ro
    ports:
      - 27017:27017

app.py

def get_db():
    client = MongoClient(host='test_mongodb',
                         port=27017,
                         username='admin',
                         password='password',
                         authSource='admin')
    db = client["staff_db"]
    print("connection good")
    return db


@app.route('/location')
def get_staff_location():
    db = ""
    staffs = []
     try:
        db = get_db()
        _staffs = db.beaconLocation_tb.find()

        for staff in _staffs:
            temp_dict = {
                "id": staffLocation["id"],
                "staffid": staffLocation["staffid"],
                "name": staffLocation["name"]
            }
            staffs.append(temp_dict)
    
        return jsonify({'staff': staffs})
    except:
        pass
    finally:
        if type(db) == MongoClient:
           db.close()

init-db.js

db = db.getSiblingDB("staff_db");
db.staff_tb.drop();

db.staff_tb.insertMany([
    {
        "id":1,
        "staffid": 1,
        "name": "Darren"
    },
    {
        "id": 2,
        "staffid": 2,
        "name": "Tony"
    },
]);

ERROR MESSAGE

pymongo.errors.ServerSelectionTimeoutError: test_mongodb:27017: [Errno -3] Temporary failure in name resolution, Timeout: 30s, Topology Description: <TopologyDescription id: 6194ffbbbce36c5d06b983f6, topology_type: Single, servers: [<ServerDescription ('test_mongodb', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('ict3102_mongodb:27017: [Errno -3] Temporary failure in name resolution')>]>

Anyone could see the error I made?

CodePudding user response:

hostname: in a Compose setup does almost nothing. If you docker exec to a get a shell in a container and the shell prompt displays the local host name, that setting will change the host name that gets displayed there, but that's almost the only impact it will have at all. You usually don't need to set this option.

Conversely, the Compose service name can be used as a host name for communication between containers. This setup is described further in Networking in Compose in the Docker documentation.

  mongodb:                    # <-- this is a valid host name
    image: mongo:latest
    # hostname: test_mongodb  # <-- does nothing, remove it
    ports:                    # <-- optional and ignored for connections
      - 27017:27017           #     between containers; always use 27017

I'd recommend making your database connection information configurable via environment variables. Note that the host name you need to connect to this MongoDB instance will be different if you're connecting from a container or from your development environment outside of Docker.

# If the environment variable is unset (you're running it from a
# non-Docker virtual environment) use a reasonable default for a
# local developer
client = MongoClient(os.environ.get('MONGODB_HOST', 'localhost'), ...)
version: '3.8'
services:
  application:
    build: .
    environment:
      MONGODB_HOST: mongodb  # its Compose service name, not its hostname:
  • Related