Kevin Vincent
Kevin Vincent

Reputation: 617

How to use mongoDB container in docker compose with flask

I'm trying to connect all my services by using docker compose. All my services are connected except mongoDB. Here is my docker-compose.yml:

version: '2'
services:
  user_service:
    build: ./user_service
    ports:
     - "83:83"
    links:
     - mongo
    depends_on:
     - mongo
    volumes:
     - .:/code
  mongo:
    image: "mongo:latest"
    ports:
     - "27017:27017"
    command: mongod --port 27017

In my flask app I try to have access to the database with the following code:

mongo = MongoClient('mongo://mongo', 27017)
db = mongo['user-database']
users = db.users.find({})

These lines of code doesn't work because my user_services doesn't find the mongoDB service.

Upvotes: 1

Views: 3791

Answers (1)

Ashan
Ashan

Reputation: 19738

In your MongoClient change the code to following

import os
from flask import Flask, redirect, url_for, request, render_template
from pymongo import MongoClient
mongo = MongoClient( os.environ['DB_PORT_27017_TCP_ADDR'],
            27017)

Reference article

This could be done using the mongodb linked container predefined environment variables that becomes available upon linking to user_service and use it in MongoClient.

Note: Check the environment variables available to your user_service container for the particular version of Mongodb container linked.

Upvotes: 2

Related Questions