on Writings, Tutorials, IBM, Bluemix, MongoDB, Code

MEAN stack on IBM Bluemix: configuring MongoDB

This is a follow up to a previous post: "The MEAN Stack on Heroku", which looked at deploying and building a MEAN stack application in the cloud via Heroku.

This time, I'm doing the exact same thing on IBM Bluemix, but this time I will focus primarily on configuring the Bluemix MongoDB service, as the rest is the same as when using Heroku.

Configuring MongoLab on Bluemix

You first need to install the MongoLab service on Bluemix and register it to your app. You can do that using cloud foundry from the command line, or just add it from the web interface.

Once MongoLab is installed and connected to your app, you’ll need to ensure your mongoose connection is set to use Bluemix's environmental variable, as well as your own (so you don't break how things work locally). That can be done by altering the way you connect to the database usingmongoose.connect(). For my app, I altered my db.js file to following:

if (process.env.VCAP_SERVICES)  
{
      var env = JSON.parse(process.env.VCAP_SERVICES);

      for (var svcName in env)
      {
            if (svcName.match(/^mongo.*/))
            {
               mongoose.connect(env['mongolab'][0].credentials.uri);
               console.log ("Connected to mongodb service");

            }
       }
}
else{

mongoose.connect('mongodb://localhost/social');

}

Bluemix stores the mongodb connection variable in an environmental variable called VCAP_SERVICES, so we need to find it and use it within mongoose.connect(). Here's what's happening in the above code snippet: 

  • In line 3, we store the VCAP_SERVICES variable into a local variable called env  
  • In line 5, we loop through the different service names stored in env
  • line 6 is a check to see if any service names match 'mongo'
  • If so, we can be sure our service is installed correctly. The mongolab service variable holds an array of information - one of which is details, which holds our connection URI - which we can use to connect with (line 8)

 Apart from doing this there's one more bit that needs fixing before the app will run:

Set the port 

When creating a node server locally, it's pretty standard to use port 3000. However, I found Bluemix doesn't like this, as it also has its own environmental variable for the port too: process.env.VCAP_APP_PORT, which you can use like so:

var port = 3000;  
if (process.env.VCAP_APP_PORT !== null) {  
    port = process.env.VCAP_APP_PORT;
}

app.listen(port, function(){

    console.log('listening on ', 3000)

})

 

Updates

  • See here for a better way to access VCAP_SERVICES