Connection refused to mongodb in docker container [duplicate] - mongodb

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>"+q['md5']+"</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?

Related

Failed Authentication when connecting with Flask through PyMongo to MongoDB in Docker Compose

I'm using Docker Compose and trying to make two containers talk to each other. One runs a MongoDB database and the other one is a Flask app that needs to read data from the first one using PyMongo.
The Mongo image is defined with the following Dockerfile:
FROM mongo:6.0
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD admin-pwd
ENV MONGO_INITDB_DATABASE admin
COPY mongo-init.js /docker-entrypoint-initdb.d/
EXPOSE 27017
And my data is loaded through the following mongo-init.js script:
db.auth('admin','admin-pwd')
db = db.getSiblingDB('quiz-db')
db.createUser({
user: 'quiz-admin',
pwd: 'quiz-pwd',
roles: [
{
role: 'readWrite',
db: 'quiz-db'
}
]
});
db.createCollection('questions');
db.questions.insertMany([
{
question: "Do you like sushi?",
answers: {
0:"Yes",
1:"No",
2:"Maybe"
}
}
]);
The Flask app is pretty straightforward. I'll skip the Dockerfile for this one as I don't think it's important to the issue. I try to connect to the database with the following code:
from flask import Flask, render_template
from pymongo import MongoClient
app = Flask(__name__)
MONGO_HOST = "questions-db"
MONGO_PORT = "27017"
MONGO_DB = "quiz-db"
MONGO_USER = "quiz-admin"
MONGO_PASS = "quiz-pwd"
uri = "mongodb://{}:{}#{}:{}/{}?authSource=quiz-db".format(MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB)
client = MongoClient(uri)
db=client["quiz-db"]
questions=list(db["questions"].find())
I'm not an expert when it comes to Mongo, but I've set authSource to 'quiz-db' since that's the database where I've created the user in the 'mongo-init.js' script. I tried to run the database container alone and I did successfully log in using mongosh with the user 'quiz-db'. All the data is there and everything works fine.
The problem is only coming up when trying to connect from the Flask app. Here's my Docker compose file:
version: '3.9'
services:
#Flask App
app:
build: ./app
ports:
- "8000:5000"
depends_on:
- "questions-db"
networks:
- mongo-net
#Mongo Database
questions-db:
build: ./questions_db
hostname: questions-db
container_name: questions-db
ports:
- "27017:27017"
networks:
- mongo-net
networks:
mongo-net:
driver: bridge
When I run 'docker compose up' I get the following error on the Flask container startup:
pymongo.errors.OperationFailure: command find requires authentication
full error: {'ok': 0.0, 'errmsg': 'command find requires authentication', 'code': 13, 'codeName': 'Unauthorized'}
MongoDB stores all user credentials in the admin database, unless you are using a really ancient version.
Use authSource=admin in the URI

Running command during docker compose or docker build failed

I am trying to build mongo inside docker and I want to push database, collection and document inside the collection I tried with docker build and below my Dockerfile
FROM mongo
RUN mongosh mongodb://127.0.0.1:27017/demeter --eval 'db.createCollection("Users")'
RUN mongosh mongodb://127.0.0.1:27017/demeter --eval 'var document = {"_id": "61912ebb4b6d7dcc7e689914","name": "Test Account","email":"test#test.net", "role": "admin", "company_domain": "test.net","type": "regular","status": "active","createdBy": "61901a01097cb16e554f5a19","twoFactorAuth": false, "password": "$2a$10$MPDjDZIboLlD8xpc/RfOouAAAmBLwEEp2ESykk/2rLcqcDJJEbEVS"}; db.Users.insert(document);'
EXPOSE 27017
and using Docker Compose
version: '3.9'
services:
web:
build:
context: ./server
dockerfile: Dockerfile
ports:
- "8080:8080"
demeter_db:
image: "mongo"
volumes:
- ./mongodata:/data/db
ports:
- "27017:27017"
command: mongosh mongodb://127.0.0.1:27017/demeter --eval 'db.createCollection("Users")'
demeter_redis:
image: "redis"
I want to add the below records because the Web Server is using them in backend. if there is a better way of doing it I would be thankful.
What I get is the below error
demeter_db_1 | Current Mongosh Log ID: 61dc697509ee790cc89fc7aa
demeter_db_1 | Connecting to: mongodb://127.0.0.1:27017/demeter?directConnection=true&serverSelectionTimeoutMS=2000
demeter_db_1 | MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
Knowing when I connect to interactive shell inside mongo container and add them manually things works fine.
root#8b20d117586d:/# mongosh 127.0.0.1:27017/demeter --eval 'db.createCollection("Users")'
Current Mongosh Log ID: 61dc64ee8a2945352c13c177
Connecting to: mongodb://127.0.0.1:27017/demeter?directConnection=true&serverSelectionTimeoutMS=2000
Using MongoDB: 5.0.5
Using Mongosh: 1.1.7
For mongosh info see: https://docs.mongodb.com/mongodb-shell/
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).
You can opt-out by running the disableTelemetry() command.
------
The server generated these startup warnings when booting:
2022-01-10T16:52:14.717+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
2022-01-10T16:52:15.514+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
------
{ ok: 1 }
root#8b20d117586d:/# exit
exit
Cheers

connecting scrapy container to mongo container

I am trying to spin and connect two containers (mongo and scrapy spider) using docker-compose. Being new to Docker I've had a hard time troubleshooting networking ports (inside and outside the container). To respect your time I'll keep it short.
The problem:
Can't connect the spider to the mongo db container and get a timeout error. I think it has to with the IP address that I am trying to connect to from the container is incorrect. However, the spider works locally (non-dockerized version) and can pass data to a running mongo container.
small edit to remove name and email from code.
error:
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5feb8bdcf912ec8797c25497, topology_type: Single
pipeline code:
from scrapy.exceptions import DropItem
# scrappy log is deprecated
#from scrapy.utils import log
import logging
import scrapy
from itemadapter import ItemAdapter
import pymongo
class xkcdMongoDBStorage:
"""
Class that handles the connection of
Input:
MongoDB
Output
"""
def __init__(self):
# requires two arguments(address and port)
#* connecting to the db
self.conn = pymongo.MongoClient(
'127.0.0.1',27017) # works with spider local and container running
# '0.0.0.0',27017)
# connecting to the db
dbnames = self.conn.list_database_names()
if 'randallMunroe' not in dbnames:
# creating the database
self.db = self.conn['randallMunroe']
#if database already exists we want access
else:
self.db = self.conn.randallMunroe
#* connecting to the table
dbCollectionNames = self.db.list_collection_names()
if 'webComic' not in dbCollectionNames:
self.collection = self.db['webComic']
else:
# the table already exist so we access it
self.collection = self.db.webComic
def process_item(self, item, spider):
valid = True
for data in item:
if not data:
valid = False
raise DropItem("Missing {0}!".format(data))
if valid:
self.collection.insert(dict(item))
logging.info(f"Question added to MongoDB database!")
return item
Dockerfile for the spider
# base image
FROM python:3
# metadata info
LABEL maintainer="first last name" email="something#gmail.com"
# exposing container port to be the same as scrapy default
EXPOSE 6023
# set work directly so that paths can be relative
WORKDIR /usr/src/app
# copy to make usage of caching
COPY requirements.txt ./
#install dependencies
RUN pip3 install --no-cache-dir -r requirements.txt
# copy code itself from local file to image
COPY . .
CMD scrapy crawl xkcdDocker
version: '3'
services:
db:
image: mongo:latest
container_name: NoSQLDB
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
volumes:
- ./data/bin:/data/db
ports:
- 27017:27017
expose:
- 27017
xkcd-scraper:
build: ./scraperDocker
container_name: xkcd-scraper-container
volumes:
- ./scraperDocker:/usr/src/app/scraper
ports:
- 5000:6023
expose:
- 6023
depends_on:
- db
Thanks for the help
Try:
self.conn = pymongo.MongoClient('NoSQLDB',27017)
Within docker compose you reference other containers based on the service name.

Docker failed to run entry-point

So I have created a node/mongo app and I am trying to run everything on docker.
I can get everything to run just fine until I try and add the init file for the mongo instance into the entry-point.
Here is my docker file for mongo: (Called mongo.dockerfile in /MongoDB)
FROM mongo:4.2
WORKDIR /usr/src/mongo
VOLUME /docker/volumes/mongo /user/data/mongo
ADD ./db-init /docker-entrypoint-initdb.d
CMD ["mongod", "--auth"]
The db-init folder contains an init.js file that looks like so (removed the names of stuff):
db.createUser({
user: '',
pwd: '',
roles: [ { role: 'readWrite', db: '' } ]
})
Here is my docker-compose file:
version: "3.7"
services:
web:
container_name: web
env_file:
- API/web.env
build:
context: ./API
target: prod
dockerfile: web.dockerfile
ports:
- "127.0.0.1:3000:3000"
depends_on:
- mongo
links:
- mongo
restart: always
mongo:
container_name: mongo
env_file:
- MongoDB/mongo.env
build:
context: ./MongoDB
dockerfile: mongo.dockerfile
restart: always
The exact error I get when running a docker-compose up is:
ERROR: for mongo Cannot start service mongo: OCI runtime create failed: container_linux.go:346: starting container process caused "exec: \"docker-entrypoint-initdb.d\": executable file not found in $PATH": unknown
I had this working at one point with another project but cannot seem to get this on to work at all.
Any thoughts on what I am doing wrong?
Also note I have seen other issues like this saying to chmod +x the path (tried that didnt work)
Also tried to chmod 777 also didnt work. (Maybe I did this wrong and I dont know exactly what to run this on?)
Your entrypoint has been modified from the upstream image, and it's not clear how from the input you've provided. You may have modified the mongo image itself and need to pull a fresh copy with docker-compose build --pull. Otherwise, you can force the entrypoint back to the upstream value:
ENTRYPOINT ["docker-entrypoint.sh"]

MongoNetworkError when connecting from different container

PHP dev new to NodeJS and I am struggling to get my NodeJS container to connect to my MongoDB container. As far I can see I have all the correct NPMs installed in my Docker file and the docker-compose is correct. Please note that I have not added the containers to the same network or but in the link to the db service into the nodejs container, although I did try this and got pretty much the same result.
Unsure why I am getting the error below when I bash into the nodejs container and run node app.js
Error
[nodemon] clean exit - waiting for changes before restart
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
(node:92) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Server is listening on port 3000
Could not connect to the database. Exiting now... { MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED localhost:27017]
at Pool.<anonymous> (/usr/src/app/node_modules/mongodb/lib/core/topologies/server.js:431:11)
at Pool.emit (events.js:193:13)
at createConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:559:14)
at connect (/usr/src/app/node_modules/mongodb/lib/core/connection/pool.js:973:11)
at makeConnection (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:39:11)
at callback (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:261:5)
at Socket.err (/usr/src/app/node_modules/mongodb/lib/core/connection/connect.js:286:7)
at Object.onceWrapper (events.js:281:20)
at Socket.emit (events.js:193:13)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at processTicksAndRejections (internal/process/task_queues.js:81:17)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
docker-compose.yml
version: '3.5' # We use version 3.5 syntax
services: # Here we define our service(s)
frontend:
container_name: angular
build: ./angular_app
volumes:
- ./angular_app:/usr/src/app
ports:
- 4200:4200
command: >
bash -c "npm install && ng serve --host 0.0.0.0 --port 4200"
depends_on:
- api
# NodeJS/Express service for API
api:
image: nodeexpress
build:
context: ./node_server
dockerfile: Dockerfile
volumes:
- ./node_server:/usr/src/app
- /usr/src/app/node_modules
ports:
- 3000:3000
links:
- mongoservice
depends_on:
- mongoservice
# Mongo database service
mongoservice:
image: mongo
container_name: mongocontainer
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: ${DB_MONGO_ROOTUSER}
MONGO_INITDB_ROOT_PASSWORD: ${DB_MONGO_ROOTPWD}
ports:
- ${DB_MONGO_EXTERNAL_PORT}:${DB_MONGO_INTERNAL_PORT}
volumes:
- ${DB_MONGO_VOLUME1}
volumes:
data:
external: true
networks:
default:
driver: bridge
Dockerfile (for api service - nodejs express)
FROM node:11-alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . .
RUN npm install
#RUN npm install mysql
RUN npm install mongodb --save
#RUN npm install --save body-parser express mysql2 sequelize helmet cors
RUN npm install --save body-parser express mongoose helmet cors
RUN npm install --save nocache
RUN npm install nodemon --save
EXPOSE 4300
#CMD ["npm", "run", "start"]
CMD [ "npm", "run", "start.dev" ]
app.js
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json());
// Configuring the database
const dbConfig = require('./config/database.config');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Connecting to the database
// Connection string variants attempted
// mongodb://root:secret#0.0.0.0:27017/angapp2
// mongodb://root:secret#127.0.0.1:27017/angapp2
// mongodb://root:secret#mongoservice:27017/angapp2
mongoose.connect('mongodb://root:secret#localhost:27017/angapp2', {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});
// Require Notes routes
require('./routes/note.routes.js')(app);
// listen for requests
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});
What I've tried:
Attempted the various connection string variants in terms of the host name, i.e. localhost, 127.0.0.1, 0.0.0.0, mongoservice
Also ran docker inspect <container-id> on the mongo service and got the internal IP address of the container and tried that in the connection string
Added RUN npm install mongodb --save to node servers Dockerfile
Managed to connect Robo 3D GUI to the Mongo container without issue
Bashed into Mongo service and managed to log into the DB and run some statements as a test that the service was working fine.
Maybe its just me being blind but, it seems that you are trying to connect to your Database on Port 27017 but in your Docker-Compose File you set the Port of the Database to 8081. Try Matching the ports.