简体   繁体   中英

Connection refused [Errno 111] when trying to access to MongoDB with Docker

i'm new to docker, i have a simple Flask program that prints data from MongoDB to an HTML page. When i execute the app using Python it works like a charm. However, using Docker i get the message :

pymongo.errors.ServerSelectionTimeoutError: 0.0.0.0:27017: [Errno 111] Connection refused

I've tried changing :

db = MongoClient('mongodb:27017').mydatabase

to one of these

db = MongoClient('mongodb://mongodb:27017').mydatabase
db = MongoClient('localhost:27017').mydatabase
db = MongoClient('0.0.0.0:27017').mydatabase

and nothing worked.

My app.py file:

from flask import Flask, render_template
import database.config as db_conf
from base64 import b64encode
from altair import Chart
from pymongo import MongoClient
import os
app = Flask(__name__)
db = MongoClient('mongodb:27017/').mydatabase

@app.route('/', methods=['GET'])
def get_all_images():
    pictures = db.pictures
    output = []
    html_body = "<ul>"
    collection = pictures.find()
    if collection:
        for q in collection:
            html_body += " <li><a href="+q['md5']+">"+q['md5']+"</a></li>"

            output.append({'md5': q['md5'], 'md5': q['md5'], 'height': q['height'], 'width': q['width'],
                           'timestamp': q['timestamp']})
        html_body += "</ul>"
    else:
        html_body = "<p>No images on database</p>"
    return html_body.format()
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

My docker-compose.yml file:

version: '2'
services:
  app:
    build:
      context: ./
      dockerfile: ./DockerFile
    ports:
     - "5000:5000"
    links:
     - mongo
    depends_on:
     - mongo
    volumes:
     - .:/code
  mongo:
    image: "mongo:latest"
    ports:
     - "27017:27017"
    command: mongod --port 27017 --bind_ip 0.0.0.0

My Docker file:

FROM python:3.6
WORKDIR /app
COPY . /app
RUN pip install --trusted-host pypi.python.org -r requirements.txt
CMD ["python", "app.py"]

I executed my script on WINDOWS 10 using :

docker-compose build
docker-compose up

According to the Compose file, your Mongo host is called mongo , not mongodb . Try

db = MongoClient('mongo:27017/').mydatabase

maybe?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM