Reputation: 7419
I am trying to dockerize a node
application that I have which uses a mongodb
instance. I am trying to point it to 'mongodb://mongo:27018/eugenie_cp'
but it keeps going to 127.0.0.1:27017
I have followed these two questions likely to be marked duplicate with but I have already used the answers from there:
Cannot connect to MongoDB via node.js in Docker
MongoDB on with Docker "failed to connect to server [localhost:27017] on first connect "
I am getting the error due to the following line, but I am not able to solve it.
// call express middleware
var express = require('express');
//Initialize the app.
var app = express();
//setting the mongoose options.
var options = {
useMongoClient: true,
server: {
socketOptions: {
socketTimeoutMS: 0,
connectTimeout: 0
}
},
server: {
reconnectTries: 1000
},
replset: {
socketOptions: {
socketTimeoutMS: 0,
connectTimeout: 0
}
}
};
// Mongo instance here.
var mongoose = require('mongoose');
// setting the MongoDb connection URL / string
var mongodb_connection_url = 'mongodb://mongo:27017/eugenie_cp';
// connect to our database
mongoose.connect(mongodb_connection_url, options);
// MongoDb connection error check
var db_check = mongoose.connection;
db_check.on('error', console.error.bind(console, 'MongoDB connection error:'));
I get the following error:
app | MongoDB connection error: Error [MongoError]: failed to connect to server [127.0.0.1:27017] on first connect [Error: connect ECONNREFUSED 127.0.0.1:27017
app | at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1126:14) {
app | name: 'MongoError',
app | message: 'connect ECONNREFUSED 127.0.0.1:27017'
app | }]
My docker-compose.yml
:
version: "3"
services:
app:
depends_on:
- mongo
container_name: app
restart: always
build: .
ports:
- "3002:3002"
links:
- mongo
mongo:
container_name: mongo
image: mongo:3.2
volumes:
- ./data:/data/db
ports:
- "27018:27017"
How do I solve this error?
Upvotes: 2
Views: 658
Reputation: 60134
In docker linking or docker-compose network you should not use publish port, in service to service communication you must use expose port or another word container port, not the host port.
So update the connection string.
var mongoose = require('mongoose');
var mongodb_connection_url = 'mongodb://mongo:27017/eugenie_cp';
mongoose.connect(mongodb_connection_url, options);
Major problem was due to the code being cached. We tested with a simple .js
program to test the connection, which pointed to the right location finally, and gave us the idea that the code wasn't being refreshed.
I guess, cache invalidation is one of the big computer problems.
Started mongo first
$ docker-compose up --build -d mongo
$ docker-compose up --build -d app
And it worked.
Upvotes: 2