Docker-compose NodeJS + Mongodb with mongoose, dynamically get mongo ip container
I have an attached nodejs app linked to a mongo container. Here is the docker file and docker-compose.yml:
FROM node:boron
# Create app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json /usr/src/app/
RUN npm install
# Bundle app source
COPY . /usr/src/app
EXPOSE 3000
CMD [ "npm", "start" ]
version: "2"
services:
web:
build: .
volumes:
- .:/usr/src/app
ports:
- "3000:3000"
links:
- mongo
mongo:
image: mongo
ports:
- "27017:27017"
and here is my app.js handling mongo connection via mongoose tool:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//DB setup
mongoose.connect('mongodb://172.19.0.2/test');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
My application starts if I go to http: // localhost: 3000 on my computer and in my terminal I can see that mongo accepted the connection.
Problem:
In my app.js, I manually added the mongo container ip. I believe if I push this app to github and someone gets it. Its ipo mongo container will not be the same as the one I added manually. Is there a way to dynamize all of this so that my app automatically becomes a mongo ip container ?
source to share
This will open the Networking section in the Docker Compose tutorial. Especially this interesting point:
Each container can now look up the web hostname or db and return the corresponding container IPs. For example, moving cargo around Lviv, the code can connect to the postgres: // db: 5432 url and start using the Postgres database.
So, given your example, you can freely modify the line
mongoose.connect('mongodb://172.19.0.2/test');
in line
mongoose.connect('mongodb://mongo/test');
source to share