Cant connect to docker mongodb - node.js

I am have not used both docker and node a lot so I hope its a simple mistake. I am using docker compose. If I through a browser access,
http://localhost:27017/ I get an:
It looks like you are trying to access MongoDB over HTTP on the native
driver port.
Also logs suggest my mongodb is healty. Last line from when I tried to access through my browser I guess.
2017-01-25T21:11:13.509+0000 I JOURNAL [initandlisten] journal
dir=/data/db/journal 2017-01-25T21:11:13.509+0000 I JOURNAL
[initandlisten] recover : no journal files present, no recovery needed
2017-01-25T21:11:13.546+0000 I JOURNAL [durability] Durability thread
started 2017-01-25T21:11:13.547+0000 I JOURNAL [journal writer]
Journal writer thread started 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] MongoDB starting : pid=1 port=27017 dbpath=/data/db
64-bit host=150c248f4cc7 2017-01-25T21:11:13.568+0000 I CONTROL
[initandlisten] db version v3.0.2 2017-01-25T21:11:13.568+0000 I
CONTROL [initandlisten] git version:
6201872043ecbbc0a4cc169b5482dcf385fc464f 2017-01-25T21:11:13.569+0000
I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1e 11 Feb 2013
2017-01-25T21:11:13.569+0000 I CONTROL [initandlisten] build info:
Linux ip-10-171-120-232 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1 x86_64
BOOST_LIB_VERSION=1_49 2017-01-25T21:11:13.569+0000 I CONTROL
[initandlisten] allocator: tcmalloc 2017-01-25T21:11:13.569+0000 I
CONTROL [initandlisten] options: {} 2017-01-25T21:11:13.573+0000 I
NETWORK [initandlisten] waiting for connections on port 27017
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44148 #1 (1 connection now open)
2017-01-25T21:11:17.843+0000 I NETWORK [initandlisten] connection
accepted from 172.20.0.1:44146 #2 (2 connections now open)
2017-01-25T21:11:17.853+0000 I NETWORK [conn2] end connection
172.20.0.1:44146 (1 connection now open) 2017-01-25T21:11:17.998+0000 I NETWORK [conn1] end connection 172.20.0.1:44148 (0 connections now
open)
So it looks that my mongodb is up running. When I in in my node application try to access it I get.
{ MongoError: failed to connect to server [localhost:27017] on first
connect
at Pool. (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:326:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection. (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at Object.onceWrapper (events.js:290:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket. (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:175:49)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13) name: 'MongoError', message: 'failed to connect to server [localhost:27017] on first connect' }
My code trying to access the mongodb
const express = require('express');
const gh = require('./src/fetch');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myApp';
// Constants
const PORT = 8888;
// App
const app = express();
app.get('/', function (req, res) {
MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err);
} else {
console.log("Connected correctly to server");
db.close();
}
});
res.send('Hello world\n');
});
app.listen(PORT);
console.log('Running on http://localhost:' + PORT);
My docker-compose looks like this.
version: '2'
services:
web:
image: gh-api
ports:
- "8888:8888"
environment:
- KEY=abc
restart: always
links:
- mongoDB
depends_on:
- mongoDB
mongoDB:
image: mongo:3.0.2
ports:
- "27017:27017"
Dockerfile for gh-api
FROM node:7.4-onbuild
EXPOSE 8888

Could you change url to your mongodb from:
const url = 'mongodb://localhost:27017/myApp';
to
const url = 'mongodb://mongoDB/myApp';
I had similar issue with my demo blog application and with that change application started working.
Edit
The best explanation that I could found is explanation of docker-compose links.
Containers for the linked service will be reachable at a hostname
identical to the alias, or the service name if no alias was specified.
So in order to access mongoDB container from web container you should use mongoDB as host name in web container.

It looks like you are trying to access MongoDB over HTTP on the native driver port.
That port is to be used by the mongo driver. If you really want/need to access the rest interface you have to use port 28017 and start mongo with the --rest flag. An example:
$ docker run --rm -p 28017:28017 mongo mongod --rest
To access a container from another, with docker compose use the service name, as pointed out by Ivan.

In my case everything was correctly setup just like answered in this question however I got this error caused by "boot race", basically my Node app would boot before mongo image and therefore it would try to connect to mongo before it's up and running. So I changed my connection code to retry again with something like this:
init().then((mongo) => main({ mongo })).catch(e => init())
function init(){
return MongoClient.connect(mongoConnectionURL)
}
function main({ mongo }){
const server = express()
server.listen(port, host);
}
I tought, this was supposed to be solved using depends_on property inside compose file, but as far as I understand, depends_on only makes sure to start other services, doesn't make sure they were initialized in proper order.

Related

Local MongoDB server not starting

I am starting to learn NodeJS and Express framework. I was following a tutorial where I had a basic application
const express = require('express');
const exphbs = require('express-handlebars');
const mongoose = require('mongoose');
const app = express();
mongoose.Promise = global.Promise
// mongoose
mongoose.connect('mongodb://localhost/vidjot-dev')
.then(() => console.log("Mongo DB started"))
.catch(err => console.error(err));
// handlebars middleware
app.engine('handlebars', exphbs({
defaultLayout: 'main'
}));
app.set('view engine','handlebars')
// index route
app.get('/', (req, res) =>{
const title = "Welcome"
res.render('index',{
title : title
});
});
app.get('/about', (req,res) =>{
res.render('about');
});
const port = 5000;
app.listen(port, () => {
console.log(`Server started on port ${port}`);
});
I tried to start the node js server from the console using the command
nodemon app
Where app is the name of the JS file app.js
When I tried to start the server, I got this error
{ MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/topologies/server.js:503:11)
at emitOne (events.js:116:13)
at Pool.emit (events.js:211:7)
at Connection.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/connection/pool.js:326:12)
at Object.onceWrapper (events.js:317:30)
at emitTwo (events.js:126:13)
at Connection.emit (events.js:214:7)
at Socket.<anonymous> (/Users/sriramr/Desktop/node/vidjot/node_modules/mongodb-core/lib/connection/connection.js:245:50)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
name: 'MongoNetworkError',
message: 'failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]' }
I tried setting the DB path again but it wasn't of any use. I tried to start mongod from the terminal but got the same error again. How do I fix this?
EDIT:
I have the directories data/db created and I just ran
mongod --dbpath <DIRECTORY>
and got this error
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] MongoDB starting : pid=76227 port=27017 dbpath=/Users/sriramr/mongodb/data/db 64-bit host=MACBOOKs-MacBook-Air.local
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] db version v3.6.2
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] git version: 489d177dbd0f0420a8ca04d39fd78d0a2c539420
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] OpenSSL version: OpenSSL 0.9.8zh 14 Jan 2016
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] allocator: system
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] modules: none
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] build environment:
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] distarch: x86_64
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] target_arch: x86_64
2018-02-16T17:42:02.657+0530 I CONTROL [initandlisten] options: { storage: { dbPath: "/Users/sriramr/mongodb/data/db" } }
2018-02-16T17:42:02.659+0530 I - [initandlisten] Detected data files in /Users/sriramr/mongodb/data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2018-02-16T17:42:02.660+0530 I STORAGE [initandlisten] exception in initAndListen: InvalidOptions: Requested option conflicts with current storage engine option for directoryPerDB; you requested false but the current server storage is already set to true and cannot be changed, terminating
2018-02-16T17:42:02.661+0530 I NETWORK [initandlisten] shutdown: going to close listening sockets...
2018-02-16T17:42:02.661+0530 I NETWORK [initandlisten] removing socket file: /tmp/mongodb-27017.sock
2018-02-16T17:42:02.661+0530 I CONTROL [initandlisten] now exiting
2018-02-16T17:42:02.661+0530 I CONTROL [initandlisten] shutting down with code:100
Open terminal/CMD and start your MongoDB server using command mongod
This command will start MongoDB for you and so your app can connect to it on localhost:27017
Are you sure you are running mongo? Your URL points to localhost, which means you need to be serving it (Separate from serving your app with nodemon).
This link shows how to run mongo from shell

Node not connecting to hosted mongodb server, failed to connect to sever on first connect

I have a Godaddy hosted website that I'm trying to have node connect from to my Godaddy Mongo server. I can get it to connect to the hosted server if I run on my mac os localhost with the exact same files.
I'm running a MEAN stack app on my hosted site, and the mongo server is using bitnami.
When I SSH into my godaddy hosted site, then run node server/server.js it gives me the following error:
toldhandyman#a2plcpnl0843 [~/public_html]$ node server/server.js
events.js:163
throw er; // Unhandled 'error' event
^
MongoError: failed to connect to server [45.40.179.118:27017] on
first connect [MongoError: connect ECONNREFUSED 45.40.179.118:27017]
at Pool.<anonymous>
(/home/toldhandyman/public_html/node_modules/mongodb-
core/lib/topologies/server.js:327:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:191:7)
at Connection.<anonymous>
(/home/toldhandyman/public_html/node_modules/mongodb-
core/lib/connection/pool.js:274:12)
at Object.onceWrapper (events.js:293:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:194:7)
at Socket.<anonymous>
(/home/toldhandyman/public_html/node_modules/mongodb-
core/lib/connection/connection.js:177:49)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at emitErrorNT (net.js:1283:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
Thats my main problem I'm having. I've been searching through this site and others for days with no success. My server.js works with my localhost using the server call:
In my config file.
MONGO_URI: 'mongodb://root:<my password here>#45.40.179.118:27017
/told-handyman?authSource=admin',
In my server.js file.
mongoose.connect(mongoURI);
When I use the same code on my hosted site it gave me the previous error
MongoError: failed to connect to server [45.40.179.118:27017] on
first connect [MongoError: connect ECONNREFUSED 45.40.179.118:27017].
The Godaddy server is using Bitnami mongodb. I've tried looking through their docs, godaddy support and many other places. I've tried changing the port to 27018. Editing the file "mongodb.conf" in bitnami#told-handyman:/opt/bitnami/mongodb/mongodb.conf hasn't helped either when working with the lines:
#bind_ip = 127.0.0.1
#bind_ip = 0.0.0.0
port = 27017
I've also tried adding different users for the db, and logging in with those credentials, but that only worked on localhost. I've also tried stopping the server and restarting it a few times.
I've made sure that it does get to the dbpath=/data/db.
Another problem I've noticed is getting mongod to work in my server when I SSH into it. Without running mongod, my localhost connects and works fine with the hosted server. When I run the line in my bitnami mongo server it shows:
bitnami#told-handyman:~$ mongod
2017-04-19T10:56:19.582-0700 I CONTROL [initandlisten] MongoDB
starting : pid=14692 port=27017 dbpath=/data/db 64-bit host=told-
handyman
2017-04-19T10:56:19.583-0700 I CONTROL [initandlisten] db version
v3.4.3
2017-04-19T10:56:19.583-0700 I CONTROL [initandlisten] git version:
f07437fb5a6cca07c10bafa78365456eb1d6d5e1
2017-04-19T10:56:19.583-0700 I CONTROL [initandlisten] allocator:
tcmalloc
2017-04-19T10:56:19.583-0700 I CONTROL [initandlisten] modules: none
2017-04-19T10:56:19.584-0700 I CONTROL [initandlisten] build
environment:
2017-04-19T10:56:19.584-0700 I CONTROL [initandlisten] distarch:
x86_64
2017-04-19T10:56:19.584-0700 I CONTROL [initandlisten]
target_arch: x86_64
2017-04-19T10:56:19.584-0700 I CONTROL [initandlisten] options: {}
2017-04-19T10:56:19.611-0700 E NETWORK [initandlisten] listen():
bind() failed Address already in use for socket: 0.0.0.0:27017
2017-04-19T10:56:19.612-0700 E NETWORK [initandlisten] addr
already in use
2017-04-19T10:56:19.612-0700 E NETWORK [initandlisten] Failed to set
up sockets during startup.
2017-04-19T10:56:19.612-0700 E STORAGE [initandlisten] Failed to set
up listener: InternalError: Failed to set up sockets
2017-04-19T10:56:19.612-0700 I NETWORK [initandlisten] shutdown:
going to close listening sockets...
2017-04-19T10:56:19.612-0700 I NETWORK [initandlisten] shutdown:
going to flush diaglog...
2017-04-19T10:56:19.612-0700 I CONTROL [initandlisten] now exiting
2017-04-19T10:56:19.612-0700 I CONTROL [initandlisten] shutting down
with code:48
bitnami#told-handyman:~$
It works when I run mongod --port 27018, and runs properly on localhost. I'm thinking that getting "mongod" to work right might be part of the problem in having my hosted site connect to my mongo server.
To sum up my problem, I have a Godaddy hosted website that can't connect to my Godaddy cloud Mongo server. I can SSh into both, and have node installed on the hosted site. Also running mongod on the server throws an error, but somehow the server still runs with my localhost without even entering that command.
Does anyone know how to fix this problem of connecting my server.js file through node to my mongo server? Am I missing anything about connecting a hosted website to a hosted server thats different from running both locally?
This is my first question here on SO. Thank you for your time and help.

docker Error while trying to connect to mongodb

I want to make simple restful API. I am using docker to do this. Here is my Dockerfile:
FROM mongo:3.2
EXPOSE 3000
RUN apt-get update; apt-get install curl -y
RUN curl -sL https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
ADD . .
CMD node app.js
My docker-compose.yml looks like this:
version: '2'
services:
db:
build: ../images/mongodb
ports:
- "27017:27017"
- "3000:3000"
my app.js file looks like this:
var express = require('express')
var app = express()
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1:27017/sample');
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
When run docker-compose up --build, I am having and error:
db_1 | Example app listening on port 3000!
db_1 |
db_1 | events.js:160
db_1 | throw er; // Unhandled 'error' event
db_1 | ^
db_1 | MongoError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
db_1 | at Pool.<anonymous> (/node_modules/mongodb-core/lib/topologies/server.js:327:35)
db_1 | at emitOne (events.js:96:13)
db_1 | at Pool.emit (events.js:188:7)
db_1 | at Connection.<anonymous> (/node_modules/mongodb-core/lib/connection/pool.js:274:12)
db_1 | at Connection.g (events.js:291:16)
db_1 | at emitTwo (events.js:106:13)
db_1 | at Connection.emit (events.js:191:7)
db_1 | at Socket.<anonymous> (/node_modules/mongodb-core/lib/connection/connection.js:177:49)
db_1 | at Socket.g (events.js:291:16)
db_1 | at emitOne (events.js:96:13)
db_1 | at Socket.emit (events.js:188:7)
db_1 | at emitErrorNT (net.js:1281:8)
db_1 | at _combinedTickCallback (internal/process/next_tick.js:80:11)
db_1 | at process._tickCallback (internal/process/next_tick.js:104:9)
I have tried to go in docker machine with docker run -it mongo:3.2 /bin/bash
root#67062897d4f0:/# mongo
MongoDB shell version: 3.2.12
connecting to: test
2017-03-23T07:01:07.587+0000 W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: errno:111 Connection refused
2017-03-23T07:01:07.588+0000 E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed :
connect#src/mongo/shell/mongo.js:229:14
root#67062897d4f0:/# mongod
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] MongoDB starting : pid=29 port=27017 dbpath=/data/db 64-bit host=67062897d4f0
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] db version v3.2.12
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] git version: ef3e1bc78e997f0d9f22f45aeb1d8e3b6ac14a14
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1t 3 May 2016
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] allocator: tcmalloc
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] modules: none
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] build environment:
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] distmod: debian81
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] distarch: x86_64
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] target_arch: x86_64
2017-03-23T07:01:12.025+0000 I CONTROL [initandlisten] options: {}
2017-03-23T07:01:12.029+0000 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=8G,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-03-23T07:01:12.222+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended.
2017-03-23T07:01:12.222+0000 I CONTROL [initandlisten]
2017-03-23T07:01:12.223+0000 I CONTROL [initandlisten]
2017-03-23T07:01:12.223+0000 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-03-23T07:01:12.223+0000 I CONTROL [initandlisten] ** We suggest setting it to 'never'
2017-03-23T07:01:12.223+0000 I CONTROL [initandlisten]
2017-03-23T07:01:12.228+0000 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2017-03-23T07:01:12.228+0000 I NETWORK [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2017-03-23T07:01:12.283+0000 I NETWORK [initandlisten] waiting for connections on port 27017
^C2017-03-23T07:01:13.447+0000 I CONTROL [signalProcessingThread] got signal 2 (Interrupt), will terminate after current cmd ends
2017-03-23T07:01:13.448+0000 I FTDC [signalProcessingThread] Shutting down full-time diagnostic data capture
2017-03-23T07:01:13.453+0000 I CONTROL [signalProcessingThread] now exiting
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] shutdown: going to close listening sockets...
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] closing listening socket: 5
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] closing listening socket: 6
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] removing socket file: /tmp/mongodb-27017.sock
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] shutdown: going to flush diaglog...
2017-03-23T07:01:13.453+0000 I NETWORK [signalProcessingThread] shutdown: going to close sockets...
2017-03-23T07:01:13.453+0000 I STORAGE [signalProcessingThread] WiredTigerKVEngine shutting down
2017-03-23T07:01:13.586+0000 I STORAGE [signalProcessingThread] shutdown: removing fs lock...
2017-03-23T07:01:13.586+0000 I CONTROL [signalProcessingThread] dbexit: rc: 0
Can someone please help me solve this ?
Amazing, I'm so glad I found this thread. I am going to add some keywords to it for other people.
If you get this error message, you could be running MongoDB on your local machine while trying to access it from inside a Docker container. The reason is that inside the Docker container, localhost or 127.0.0.1 refers to a different interface than your true local machine.
Error Output:
MongoError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/app/node_modules/mongodb-core/lib/topologies/server.js:329:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:191:7)
at Connection.<anonymous> (/app/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Object.onceWrapper (events.js:293:19)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:194:7)
at Socket.<anonymous> (/app/node_modules/mongodb-core/lib/connection/connection.js:187:49)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Socket.emit (events.js:191:7)
at emitErrorNT (net.js:1284:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'MongoError',
message: 'failed to connect to server [127.0.0.1:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }
Possible Fixes:
Enable remote connections from your MongoDB, and use your public IP to access it from inside the Docker Container.
Run MongoDB from inside the Container, and then you can refer to it with localhost.
Run another Docker Container, and enable remote connections on it. Investigate bind_ip in the MongoDB config file. Make sure you secure your database with auth credentials. Spend some time ensuring it is secure.
Remote connections are disabled by default in MongoDB, ie: going through a Docker container incorrectly.
Here is a helpful resource: https://hub.docker.com/_/mongo/
The issue I believe is that using CMD node app.js only starts node and not the database. Normally when creating this kind of simple app you use two containers. One for mongo one for node, as you aren't using a custom config for mongo or node you could just use images and map the code in your current folder to the /opt/ directory in the container, meaning all you need is a compose file and potentially don't need any Dockerfile's
Disclaimer obviously this isn't good enough for production, at some point you will probably want to use a Dockerfile for your app as it's best to start node as a user instead of root and put the files in a meaningful directory. But if all you want to do is use as a sandbox this should do.
Your docker compose would look like
version: "2"
services:
db:
image: mongo:3.2
ports:
- 27017
app:
image: node
links:
- db
volumes:
- '.:/opt/'
command: node /opt/app.js
ports:
- 3000:3000
If you want to go full in and specify a Dockerfile for each.
/docker-files/app/Dockerfile
# take from the latest node build
FROM node
# Make a directory /opt/app
RUN mkdir /opt/app
# Set work dir to /opt/app
WORKDIR /opt/app
# Do all your npm install etc....
CMD node app.js
/docker-files/db/Dockerfile
FROM mongo:3.2
# Do some fancy mongo stuff.
/docker-compose.yml
version: "2"
services:
db:
build:
context: docker-files/db
dockerfile: Dockerfile
ports:
- 27017
app:
build:
context: docker-files/app
dockerfile: Dockerfile
links:
- db
volumes:
- '.:/opt/app'
ports:
- 3000:3000
For docker-compose, you need to use a tag networks to link one container node with other. Look:
version: '2'
networks:
app-tier:
driver: bridge
services:
mongodb:
image: 'mongodb:latest'
networks:
- app-net
myapp:
image: 'YOUR_APPLICATION_IMAGE'
networks:
- app-net

[Error: failed to connect to [localhost:27017]] from NodeJS to mongodb

I am having problem connecting to MongoDB from NodeJS using following sample code. I tried running "mongod" with or without sudo but nodejs code still fail to connect. I am able to successfully connect to database using "mongo".
Running on : MAC OS 10.6.8
var mongoClient = require('mongodb').MongoClient;
mongoClient.connect("mongodb://localhost:27017/test", function(error, db) {
if(!error){
console.log("We are connected");
}
else
console.dir(error);
});
get following error running above code : [Error: failed to connect to [localhost:27017]]
Also tried mongoose but similar error:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log("DB connected");
// yay!
});
Output: connection error: [Error: failed to connect to [localhost:27017]]
Here is the log of mongod
mongod --help for help and startup options
2014-07-11T23:33:47.843-0700 kern.sched unavailable
2014-07-11T23:33:47.849-0700 [initandlisten] MongoDB starting : pid=29942 port=27017 dbpath=/data/db 64-bit host=usc8bcc8a0d0b1
2014-07-11T23:33:47.849-0700 [initandlisten]
2014-07-11T23:33:47.849-0700 [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2014-07-11T23:33:47.849-0700 [initandlisten] db version v2.6.3
2014-07-11T23:33:47.849-0700 [initandlisten] git version: nogitversion
2014-07-11T23:33:47.849-0700 [initandlisten] build info: Darwin usc8bcc8a0d0b1 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun 7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386 BOOST_LIB_VERSION=1_49
2014-07-11T23:33:47.849-0700 [initandlisten] allocator: system
2014-07-11T23:33:47.849-0700 [initandlisten] options: {}
2014-07-11T23:33:47.850-0700 [initandlisten] journal dir=/data/db/journal
2014-07-11T23:33:47.850-0700 [initandlisten] recover : no journal files present, no recovery needed
2014-07-11T23:33:47.901-0700 [initandlisten] waiting for connections on port 27017
2014-07-11T23:34:47.901-0700 [clientcursormon] mem (MB) res:48 virt:2810
2014-07-11T23:34:47.901-0700 [clientcursormon] mapped (incl journal view):320
2014-07-11T23:34:47.901-0700 [clientcursormon] connections:0
Never mind, I was able to resolve the issue by using 127.0.0.1 instead of localhost, not sure why I have to use ip address. My tomcat, apache, redis, and even node server all works using localhost but not the mongodb. Is there is config I need change to make it work using local host?
Try adding 127.0.0.1 localhost in /private/etc/hosts file.
This issue can occur if your mongoDBwasnot shutdown properly
Mongodb can't connect to localhost but can connect to localhost's IP address
Start your mongoDB Server using follwoingcommand and then try same ./mongod --bind_ip localhost
yes , I came across this error too, and my hosts is as follow:
127.0.0.1 xxxxxx(the ip of my computer)
and when I ran npm start in express project, it got an error like that . After I tried to change the mapping of 127.0.0.1 to localhost, it had no error.
The first time, I made the obvious mistake that mongod (the mongo Server) was not even running.
The second time, I had both the Server (mongod) and the Client (mongo) running on my Windows; in separate Command Prompts (of course mongo running first). mongod and/or its Command Prompt was "hung up" (i.e. the last line only said this, and the last line remained like this despite attempts to connections:)
2017-06-20T12:31:02.937-0600 I NETWORK [thread1] waiting for connections on port 27017
I clicked in the Command Prompt pressed the space-bar to "kick it" , and the Command Prompt printed lines like these:
2017-06-20T12:31:48.517-0600 I NETWORK [thread1] connection accepted from 127.0.0.1:50260 #1 (1 connection now open)
Which worked!
Somebody on Github found a solution:
Instead of writing:
Mongoose.connect(config.database.url);
Write:
Mongoose.connect(config.database.url, {
keepAlive: true,
reconnectTries: Number.MAX_VALUE,
useMongoClient: true
});
(Source https://github.com/Automattic/mongoose/issues/5399)

ECONNREFUSED error when connecting to mongodb from node.js

I know I'm doing some very stupid and noobish, but I'm hoping someone can help me set up a basic database connection to mongodb from node.js on a mac.
I've installed mongodb using homebrew, seems to have worked quite well. I have started the server (mongod) as the locally logged in user, and opened a second terminal and confirmed that I can connect to it by using mongo. When I run mongo I get the message "connecting to: localhost:27017/test" followed by a command prompt. Ran a few commands in the mongo shell everything seems to be working there. Left both terminals open and running.
I've also confirmed that I can reach the web interface at localhost:28017.
I installed node.js and added the mongoose package. Now attempting to connect using a super simple node.js app (also running as locally logged in user):
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
I receive the following error
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
Banging my head against the wall trying to get something so simple to work. What am I missing?
Edit: Here are the logs from mongod. As you can see I tried multiple times and they're all failing rather instantaneously:
Thu Dec 5 08:19:43.700 [initandlisten] MongoDB starting : pid=14412 port=27017 dbpath=/usr/local/var/mongodb 64-bit host=mobadmins-MacBook-Pro-3.local
08:19:43.700 [initandlisten] db version v2.4.8
08:19:43.700 [initandlisten] git version: nogitversion
08:19:43.700 [initandlisten] build info: Darwin mobadmins-MacBook-Pro-3.local 12.4.0 Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013; root:xnu-2050.24.15~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
08:19:43.700 [initandlisten] allocator: tcmalloc
08:19:43.700 [initandlisten] options: { bind_ip: "127.0.0.1", config: "/usr/local/etc/mongod.conf", dbpath: "/usr/local/var/mongodb", logappend: "true", logpath: "/usr/local/var/log/mongodb/mongo.log", rest: true }
08:19:43.700 [initandlisten] journal dir=/usr/local/var/mongodb/journal
08:19:43.700 [initandlisten] recover : no journal files present, no recovery needed
08:19:43.729 [websvr] admin web console waiting for connections on port 28017
08:19:43.729 [initandlisten] waiting for connections on port 27017
08:22:34.561 [initandlisten] connection accepted from 127.0.0.1:52160 #3 (1 connection now open)
08:22:34.563 [conn3] recv(): message len 1124073472 is too large. Max is 48000000
08:22:34.563 [conn3] end connection 127.0.0.1:52160 (0 connections now open)
08:24:41.298 [initandlisten] connection accepted from 127.0.0.1:52166 #4 (1 connection now open)
08:24:41.304 [conn4] end connection 127.0.0.1:52166 (0 connections now open)
08:25:06.938 [initandlisten] connection accepted from 127.0.0.1:52168 #5 (1 connection now open)
08:25:06.943 [conn5] end connection 127.0.0.1:52168 (0 connections now open)
08:25:18.220 [initandlisten] connection accepted from 127.0.0.1:52172 #6 (1 connection now open)
08:25:18.225 [conn6] end connection 127.0.0.1:52172 (0 connections now open)
08:25:38.811 [initandlisten] connection accepted from 127.0.0.1:52175 #7 (1 connection now open)
08:25:38.816 [conn7] end connection 127.0.0.1:52175 (0 connections now open)
ECONNREFUSED error
There are few reasons of this error in node :
Your port is already serving some service so it will refuse your connection.
go to command line and get pid by using following command
$ lsof -i:port_number
Now kill pid by using
$ kill -9 pid(which you will get by above command)
Your server is not running e.g. in this case please check your mongoose server is running or run by using following command.
$ mongod
There is also possibility your localhost is not configured properly so use 127.0.0.1:27017 instead of localhost.
OK, this was another case of not being truly forthcoming in the info I posted above. My node.js app was very simple, but I was including another couple lines in my node.js code that apparently caused this issue.
Specifically, I had another variable declared which was calling some other code that made a separate database call using incorrect db info. This is why, when using Xinzz's code, the console log error seemed not to change. It wasn't actually the mongoose.connect command that was throwing the error!
Lesson learned, localize the problem and comment out unrelated code! Sorry guys, I knew this was me being dumb.
For me I had to change 'localhost' to '127.0.0.1' and then it started working again:
mongoose.connect('mongodb://127.0.0.1/test')
Use this code to setup your mongodb connection:
var mongoose = require('mongoose');
var mongoURI = "mongodb://localhost:27017/test";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
Make sure mongod is running while you start the server. Are you using Express or just a simple node.js server? What is the error message you get with the above code?
very strange, but in my case, i switch wifi connection...
I use some public wifi and switch to my phone connection
I had facing the same issue while writing a simple rest api using node.js
eventually found out it was due to wifi blockage and security reason .
try once connecting it using your mobile hotspot .
if this be the reason it will get resolved immediately.
I had same problem. It was resolved by running same code in Administrator Console.
I had the same issue. What I did is to run mongodb command in another terminal. Then, run my application in another tab. This resolved my problem. Though, I am trying other solution such as creating a script to run mongodb before connection is made.
sometimes you need to check the rightfulness of the IP, firewall, port forwarding, etc, if your target database is in other machines.
I had the same issue, all I did was add a setTimeout of about 10 seconds before trying to connect to the Mongo server and it solved the issue right up. I dont know why I had to add a delay but it worked...
I also got stucked with same problem so I fixed it like this :
If you are running mongo and nodejs in docker container or in docker compose
so replace localhost with mongo (which is container name in docker in my case) something like this below in your nodejs mongo connection file.
var mongoURI = "mongodb://mongo:27017/<nodejs_container_name>";
I manually started the mongodb service.
Control Panel -> Administrative tools -> Services -> Mongodb
Then either start/restart it. It's done!
Happy Coding! :-)
mongod was running fine locally on my system. I could connect to it with Mongo Compass, but mongoose simply refused to connect. The magic word is directConnection=true, as in
mongodb://127.0.0.1:27017/test?directConnection=true
Versions:
mongoose 6.5.2
mongodb 4.4.13 Community
node 18.5.0
If you're trying to connect to a remote MongoDB server and getting the ECONNREFUSED error, make sure the bind ip option is set up to 0.0.0.0.
See https://www.mongodb.com/docs/manual/core/security-mongodb-configuration/ for more information or use the MongoDB config file (mongod.conf, read more) like this:
net:
bindIp: 0.0.0.0
You can just use your local IP address (e.g. 127.0.0.1), instead of using localhost.
(localhost = 127.0.0.1:27017)
'mongodb://127.0.0.1:27017/<ele.Name>'
This is how i got my solution
Check this post. https://stackoverflow.com/a/57589615
It probably means that mongodb is not running. You will have to enable it through the command line or on windows run services.msc and enable mongodb.
I tried every possible solution,butit didn't help me. I took a break and I changed the following. Simple typo. May help someone is same situation.
From:
app.listen((port)=>console.log(Server is running at port ${PORT}))
To:
app.listen(PORT, console.log(Server is running at port ${PORT}))
The earlier got me to connect to database mongo atlas but get request was Error: connect ECONNREFUSED
you can go to mongoDB compass client and follow these steps:
1.Click Fill in connection fields individually:
2.In hostname type : 127.0.0.1
3. Click CONNECT.
Mongodb was not running but I had the module for node.js The database path was missing. Fix was create new folder in the root so run
sudo mkdir -p /data/db/
then run
sudo chown id -u /data/db
For my case this resolved:
Control Panel -> Administrative tools -> Services -> Start MongoDB Server
Hello this is fun and I mean it's fun. Headover to start button and typeservice from there ho Down to and look for mongodb.right click it and click start. Mongod will start. Go back to your project and thank me later

Resources