I have a dockerized nodejs app linked with a mongo container. Here is the dockerfile 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 the mongo connection via the 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 app launches, if I go on http://localhost:3000 on my computer my view displays and in my terminal I see that mongo accepted a connection.
Problem is :
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 the mongo container ip?
Check out Networking section in Docker Compose Manual. Especially this interesting paragraph:
Each container can now look up the hostname web or db and get back the appropriate container’s IP address. For example, web’s application code could connect to the URL postgres://db:5432 and start using the Postgres database.
So given your example, you can freely change line
mongoose.connect('mongodb://172.19.0.2/test');
to line
mongoose.connect('mongodb://mongo/test');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With