title: docker-compose NodeJS + Mongodb with mongoose, dynamically get the mongo container ip
body: <p>I have a dockerized nodejs app linked with a mongo container. Here is the dockerfile and docker-compose.yml : </p>
  
  <pre><code>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" ]
  </code></pre>
  
  <hr>
  
  <pre><code>version: "2"
  services:
    web:
      build: .
      volumes:
        - .:/usr/src/app
      ports:
        - "3000:3000"
      links:
        - mongo
    mongo:
      image: mongo
      ports:
          - "27017:27017"
  </code></pre>
  
  <p>and here is my app.js handling the mongo connection via the mongoose tool : </p>
  
  <pre><code>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;
  </code></pre>
  
  <p>My app launches, if I go on <a href="http://localhost:3000" rel="noreferrer">http://localhost:3000</a> on my computer my view displays and in my terminal I see that mongo accepted a connection.</p>
  
  <hr>
  
  <p><strong>Problem is :</strong> </p>
  
  <p>In my app.js I added manually the mongo container ip. I believe if I push this app on github and someone gets it. His mongo container ip won't be the same as the one i added manually. Is there some way to dynamise all of this so that my app gets automatically <strong>the mongo container ip</strong>?</p>