Local MongoDB server not starting - node.js

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

Related

Node.js Server not connecting to local mongodb instance

I have a node.js server that tries to connect to mongodb (working with mongoose):
mongoose.connect('mongodb://127.0.0.1:27017/ordry', {useNewUrlParser: true, useFindAndModify: false, useCreateIndex: true}).then(result =>{ // 127.0.0.1:27017
console.log("Successfully connected to db!");
}).catch(error =>{
console.log("Error connecting to the database!")
})
Although mongodb is up and running, the connection fails.
I get the following logs:
Thu Jul 18 13:24:50.124 [initandlisten] options: { dbpath: "/home/pi/mongodb/" }
Thu Jul 18 13:24:50.166 [initandlisten] waiting for connections on port 27017
Thu Jul 18 13:24:50.166 [websvr] admin web console waiting for connections on port 28017
Thu Jul 18 13:25:45.647 [initandlisten] connection accepted from 127.0.0.1:50188
1 (1 connection now open)
Thu Jul 18 13:25:45.742 [conn1] end connection 127.0.0.1:50188 (0 connections now open)
EDIT Logs from Node.js:
[nodemon] starting `node ./server/server.js`
{ MongoNetworkError: failed to connect to server [127.0.0.1:27017] on first connect [MongoError: Server at 127.0.0.1:27017 reports maximum wire version 0, but this version of the Node.js Driver requires at least 2 (MongoDB 2.6)]
at Pool.<anonymous> (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/topologies/server.js:431:11)
at Pool.emit (events.js:198:13)
at connect (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/pool.js:557:14)
at callback (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/connect.js:109:5)
at runCommand (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/connect.js:140:7)
at Connection.messageHandler (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/connect.js:334:5)
at Connection.emit (events.js:198:13)
at processMessage (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/connection.js:364:10)
at Socket.<anonymous> (/home/pi/Desktop/Ordry API/node_modules/mongodb-core/lib/connection/connection.js:533:15)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Conclusion
I am a bit unsure why it is not working here - especially as everything worked fine on windows.
I am using Raspbian on my Raspberry Pi 3b+.
Any help would be appreciated.
usually this happens because you didn't start mongod process before you try starting mongo shell.
1) Delete mongod.lock file from C:\Program
Files\MongoDB\Server\4.0\data
2) Start mongod server
In another terminal - start mongo shell
1) mongo
The error message you get:
reports maximum wire version 0, but this version of the Node.js Driver requires at least 2 (MongoDB 2.6)
Is warning you to upgrade your MongoDB version to 2.6 at least, because it's not supported by the drivers used by the wire library which MongoDB depends on.
It seems that the version of MongoDB (2.4) provided by Raspbian is not supported anymore, so the best way to run a MongoDB server os a Raspberry Pi is to install another Linux distribution like Ubuntu or Arch Linux.

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

Cant connect to docker mongodb

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.

Mongoose fails to connect to localhost: MongoError: failed to connect to server [127.0.0.1:27017]

I am working on a repo I downloaded from Github https://github.com/MessagingBots/MessengerBot, I know the js code is fine.
I have a config file directing the db URL to "mongodb://127.0.0.1:27017/messenger". (I haven't created the db yet)
I have the node app on Heroku, but Heroku Logs fail every time on mongodb connect.
2016-12-02T06:23:31.636339+00:00 app[web.1]: mongodb://127.0.0.1:27017/messenger
2016-12-02T06:23:31.672354+00:00 app[web.1]: CALLBACK URL IS
2016-12-02T06:23:31.672434+00:00 app[web.1]: https://cool-scrubland-89690.herokuapp.com/messages/receive/
2016-12-02T06:23:31.683394+00:00 app[web.1]: students
2016-12-02T06:23:31.701863+00:00 app[web.1]: listening on port 3124
2016-12-02T06:23:31.702052+00:00 app[web.1]: Application running at port 48594
2016-12-02T06:23:31.717752+00:00 app[web.1]:
2016-12-02T06:23:31.717764+00:00 app[web.1]: /app/node_modules/mongoose/node_modules/mongodb/lib/server.js:261
2016-12-02T06:23:31.717766+00:00 app[web.1]: process.nextTick(function() { throw err; })
2016-12-02T06:23:31.717767+00:00 app[web.1]: ^
2016-12-02T06:23:31.718744+00:00 app[web.1]: MongoError: failed to connect to server [127.0.0.1:27017] on first connect
2016-12-02T06:23:31.718746+00:00 app[web.1]: at Pool.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb-core/lib/topologies/server.js:313:35)
2016-12-02T06:23:31.718747+00:00 app[web.1]: at emitOne (events.js:96:13)
2016-12-02T06:23:31.718747+00:00 app[web.1]: at Pool.emit (events.js:188:7)
2016-12-02T06:23:31.718748+00:00 app[web.1]: at Connection.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/pool.js:271:12)
2016-12-02T06:23:31.718749+00:00 app[web.1]: at Connection.g (events.js:291:16)
2016-12-02T06:23:31.718750+00:00 app[web.1]: at emitTwo (events.js:106:13)
2016-12-02T06:23:31.718750+00:00 app[web.1]: at Connection.emit (events.js:191:7)
2016-12-02T06:23:31.718751+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/mongoose/node_modules/mongodb-core/lib/connection/connection.js:165:49)
2016-12-02T06:23:31.718752+00:00 app[web.1]: at Socket.g (events.js:291:16)
2016-12-02T06:23:31.718752+00:00 app[web.1]: at emitOne (events.js:96:13)
2016-12-02T06:23:31.718753+00:00 app[web.1]: at Socket.emit (events.js:188:7)
2016-12-02T06:23:31.718754+00:00 app[web.1]: at emitErrorNT (net.js:1276:8)
2016-12-02T06:23:31.718754+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:74:11)
2016-12-02T06:23:31.718755+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:98:9)
2016-12-02T06:24:24.832476+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2016-12-02T06:24:24.832543+00:00 heroku[web.1]: Stopping process with SIGKILL
2016-12-02T06:24:24.958931+00:00 heroku[web.1]: State changed from starting to crashed
2016-12-02T06:24:24.949820+00:00 heroku[web.1]: Process exited with status 137
I have a mongod instance running. mongod properly connects to localhost and is stable
2016-12-02T14:02:26.733+0700 I CONTROL [initandlisten] MongoDB starting : pid=2706 port=27017 dbpath=/data/db 64-bit host=ME.local
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] db version v3.2.11
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] git version: 009580ad490190ba33d1c6253ebd8d91808923e4
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.2j 26 Sep 2016
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] allocator: system
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] modules: none
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] build environment:
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] distarch: x86_64
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] target_arch: x86_64
2016-12-02T14:02:26.735+0700 I CONTROL [initandlisten] options: {}
2016-12-02T14:02:26.738+0700 I - [initandlisten] Detected data files in /data/db created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'.
2016-12-02T14:02:26.739+0700 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=4G,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),
2016-12-02T14:02:27.758+0700 I CONTROL [initandlisten]
2016-12-02T14:02:27.759+0700 I CONTROL [initandlisten] ** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
2016-12-02T14:02:27.763+0700 I NETWORK [HostnameCanonicalizationWorker] Starting hostname canonicalization worker
2016-12-02T14:02:27.763+0700 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'
2016-12-02T14:02:27.767+0700 I NETWORK [initandlisten] waiting for connections on port 27017
The problem might be related to Mongoose.
Anyone could help me out?
see if there is an old lock file present if present than remove it by
sudo rm /var/lib/mongodb/mongod.lock see if this works for you
sudo mongod --repair and (sudo start mongodb or sudo service mongodb start)
You haven't to precise mongodb:// in your mongoose connect call :
mongoose.connect("localhost:27017/mydbname");

Resources