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?