Follow Me Icons


Follow @KendrickColeman on TwitterConnect on LinkedInWatch My Videos on YouTubeFollow me on FacebookCheck Out My Projects on GitHubStay Up To Date with RSS


BSA 728x90 Center Banner

Deploying a Node.js WebApp with MongoDB to Cloud Foundry

I recently created a new project to help me get a better understanding of Node.js webapps using Express.js and using MongoDB on the backend. It took me a little over 2 hours to get this app properly deployed to CF and run in development at the same time. Documentation is sparse, so I'll spare you the details and just show you how it's done.



The only thing you need here is that if you are using express.js then the "npm start" needs to be setup correctly. If you used the express generator then this is done for you.

"scripts": {
    "start": "node ./bin/www"




Is this necessary? Not sure, but the documentation seemed to think so. Within the /bin folder there is a www file used to start the http server when you use the express generator. make sure the port variable looks like this:

var port = normalizePort(process.env.PORT || process.env.VCAP_APP_PORT || '3000');



Database connection:

Cloud Foundry has a nice little node package called cfenv that will get the Cloud Foundry environment variables, but doesn't show you how you would use it in a deployment scenario to keep local production working as well. First thing is first, create a MongoDB instance either through the CLI doing a 'cf push' or through the WebUI. Don't bind it to an application just yet.


Here's the code we use to get our MongoLab URL from cfenv or if it returns as false, then we are just going to connect to our local MongoDB instance




I always create a manifest.yml just because I like to keep it consistent. Change the services to whatever you named your MongoLab instance from above.

- name: mySweetNodeApp
  memory: 256M
  instances: 1
  path: .
  command: npm install && npm start
  - my-mongo-database


That's it! now you just need to do a 'cf push' and your app will be up in a few minutes


Related Items