Contents


Bluemix fundamentals: Deploy a sample Node.js application to the cloud

Intro to Node.js application development on IBM Bluemix

Comments

Overview

Get started working in the cloud using the language and tools you're already familiar with as a web developer. In this tutorial, learn how to run, modify, test, and deploy a simple Node.js app to the cloud. Once you deploy the app to Bluemix™, IBM's cloud development platform, anyone on the Internet can access it.

This tutorial is part of the "Bluemix fundamentals" tutorial series on developerWorks.

What you'll do in this tutorial

Step 1. Download the code

Step 2. Deploy the app to Bluemix

Step 3. Examine the code structure

Step 4. Run the app on your computer

Step 5. Run unit tests

Step 6. Modify the code and rerun the app

Step 7. Rerun the unit tests

Step 8. Deploy the changed code to Bluemix

Quiz time!

What's next?

Let's get started

IBM Bluemix is where enterprise developers build, run, scale, and manage applications. Ready to start creating your own apps on Bluemix? This tutorial walks you through the steps for hosting a Node.js application. You start with a sample Node.js app, run it on your local system, modify the code, and then deploy the app to Bluemix so that anyone who's online can use it.

If you're unsure about Bluemix terms and status messages you may see, head over to the Glossary and status messages section of this tutorial.

Here's a quick overview of how you'll work with Bluemix in this tutorial.

Overview diagram showing relationship between local and cloud components for deploying the sample app
Overview diagram showing relationship between local and cloud components for deploying the sample app

You run your own instance of the Node.js HTTP server with the Express web framework (I'll refer to this combination as the Express server) running in the cloud. Once the Express server is deployed successfully, it runs continuously and isn't shared by anyone.

You also run the app in an instance of the Express server on your computer. With this setup, you can quickly test and debug your app without connecting to the Internet and uploading code every time you make a change.

After you get your code running on the local server and are satisfied that it's ready for prime time, you use the Cloud Foundry CLI to upload your web app, including the Express server, to the cloud (the process represented by the dotted black arrow in the diagram). Your app is then available through Bluemix, accessible over the Internet by anyone with a browser.

Knowledge that you need for this tutorial

  • Working knowledge of Node.js development and the npm package/dependency manager
  • General knowledge of client/server system basics and terminology

Software that you need for this tutorial

Step 1. Download the code

  1. Click this button to download the code for the sample Node.js web app, nodejstutorial1.zip:
  2. Save nodejstutorial1.zip to your computer and extract its contents, which consists of the following files and directories:
    • app.js, the main executable of the app, starts the Express server that handles web requests.
    • websitetitle.js is a simple module that supplies the text for the website's title.
    • package.json describes your Node.js project and specifies all its dependencies. This file is processed by the standard npm dependency manager.
    • views is a directory that contains templates of the pages that constitute the app. Each template file can contain dynamic elements that are rendered on the fly with incoming requests.
    • public is a directory that contains all the static assets of the app, which can include CSS, images, and client-side JavaScript code that runs on the browser.
    • test is a directory that contains unit tests for the websiteTitle module.

Step 2. Deploy the app to Bluemix

This app, like most Node.js web apps, can be deployed immediately to Bluemix with no additional modification or configuration. You'll deploy it now to Bluemix:

  1. If you're not already logged in to Bluemix, run these commands from your OS command prompt to log in:

    cf api https://api.ng.bluemix.net/
    cf login

  2. Upload the app to Bluemix by running the command:

    cf push your app name

    The name you choose for your application must be unique on Bluemix — not used by any other Bluemix user. You'll get an error if the name (called a route) is taken.

    The command that you just ran:

    1. Uploads the app to Bluemix
    2. Runs the IBM SDK for Node.js buildpack in Bluemix
    3. Starts your Express server instance, with your app loaded, in Bluemix
    4. Maps a route to your running app, enabling the app to be accessed over the Internet at the URL https://your app name.mybluemix.net/
  3. Open https://your app name.mybluemix.net/ in your browser to try out the app — a simple web store called Lauren's Lovely Landscapes. The store currently sells three prints; each print's page displays the associated name, image, and price.
  4. Stop and reflect. You just finished deploying a working web application to the cloud! All you needed was the cf command-line tool and a Bluemix account.

Later in this tutorial, you'll learn more about how the buildpack works together with Bluemix to stage and deploy your app.

Starting with the next step, you'll begin to examine and modify the code. A syntax-highlighting editor with multiple-tabs support makes it much easier to work with the multiple JavaScript and template source code files.

Step 3. Examine the code structure

Take a look at the views directory from the extracted ZIP file. You can see four Jade template files — the .jade files — that make up the website.

This diagram shows how the app works:

Each web request for a page of the Lauren's Lovely Landscapes store is routed by your code to one of the templates. When routing to the template, your code attaches a JavaScript object that contains website title information. The template uses this object to render its title (Lauren's Lovely Landscapes).

In app.js, you can see the code that routes requests to a template, together with a variable containing the title from the websiteTitle object:

app.get('/', function (req, res) {
  res.render('home', {title: websiteTitle.getTitle()});
});
app.get('/alaska', function (req, res) {
  res.render('alaska',  {title: websiteTitle.getTitle()});
});
app.get('/antarctica', function (req, res) {
  res.render('antarctica',  {title: websiteTitle.getTitle()});
});
app.get('/australia', function (req, res) {
  res.render('australia',  {title: websiteTitle.getTitle()});
});

In this case, each of the four paths —/, /antarctica, /alaska, and /australia— routes to its corresponding template, along with the attached website title.

If you examine one of the templates — say, alaska.jade — you can see the use of a Jade template variable to render the title:

<head>
	<title> ${title} </title>
...

When you start the Express server, it listens on a port for incoming requests. The port used by Bluemix to connect your app to the Internet can change every time you deploy the app. However, Bluemix provides a PORT environment variable that tells the app which port to listen to. In app.js, you can see the code that fetches the environment variable and listens at the specified port:

var appEnv = cfenv.getAppEnv();
app.listen(appEnv.port, appEnv.bind, function() {
...
}

Step 4. Run the app on your computer

You're now ready to run the app locally on your computer.

  1. At the root directory of your app, run:

    npm install

    This is the standard way to tell npm to look into the package.json file and then download and install all dependencies of this app. npm creates a node_modules directory and places all the downloaded dependencies there:
  2. Start the app in the Express server:

    node app.js

    At the command console, note the port that the Express server is running on (http://localhost:6002/ in this example):
  3. Point a browser to the Express server at http://localhost:port_number.
  4. Try out this instance of the application and see if you notice any difference from the Bluemix-hosted one. Because you're looking at the same app, produced with the same code, there should be no noticeable differences between the two.

Step 5. Run unit tests

It's good Node.js coding practice to write unit tests for your modules.

  1. If you don't already have the mocha unit-testing framework installed on your system, run this command to install it:

    npm install mocha -g

  2. The app comes with two unit tests for the websitetitle.js module. Run them by starting mocha with this command:

    mocha

You can see both tests being run. In the results printed to your screen, a green check mark appears next to each passing test, and mocha reports the total number of passing tests. All unit tests passed:

Step 6. Modify the code and rerun the app

In this step, you'll modify the price of a print and see it updated on the locally running website right away.

  1. In your text editor, open up the antarctica.jade file and look for the price in the source code.
  2. Change the price from 100.00 to 99.99 and save the file. The changed line should look like:
    <div id="price">99.99</div>
  3. Run the app locally again:

    node app.js

  4. Point a browser to the Express server
  5. Select the Antarctica print and note the print's changed price.

Step 7. Rerun the unit tests

To ensure that your code changes don't break anything, get into the habit of running unit tests every time an app is modified.

Rerun the unit tests with the mocha command. Once again, in the screen output you see all green check marks and no red text, indicating that all unit tests were successful.

When you develop Node.js code in a team environment, you want to run all unit tests every single time you commit (modify and contribute) your code to the team's repository. Bluemix offers DevOps services that can be configured to run the unit tests automatically as part of the workflow to build the project. You'll learn much more about DevOps services in the next tutorial in this series.

Step 8. Deploy the changed code to Bluemix

To let everyone on the Internet know about the Antarctica print's new price, you'll deploy the changed app to Bluemix.

In Step 2, you saw how simple it is to deploy a Node.js program to Bluemix. Again, run this command from the root directory of your code:

cf push your app name

After successful deployment, try out the app by pointing any web browser to:

https://your app name.mybluemix.net/

Glossary and status messages

Let's review some terms and status messages you're likely to encounter as you use Bluemix.

Glossary

Familiarize yourself with the following important terms, which you'll often see in documentation and status messages when you work with Bluemix.

  • Droplet— A bundle ready to run in the cloud, including everything needed (for instance, a bundle with JVM, Liberty profile server, and your app) except an operating system.
  • Buildpack— An executable that takes the code or packaged server that you push, and bundles it up into a droplet.
  • Manifest— An optional file, named manifest.yml, that you can add to your project. The manifest file configures various parameters that affect the deployed server — including memory size, buildpack to use during deployment, services that are required, the disk space consumed, and so on. For simple Node.js web apps, you don't need a manifest; the system automatically detects and uses the IBM SDK for Node.js buildpack and applies a default configuration.
  • Staging— The process handled by the buildpack, bundling what you uploaded with system components and dependencies into a valid droplet
  • Droplet Execution Agent (DEA)— The system piece that's responsible for reconstituting the droplet and running your app in the cloud
  • Warden— A mechanism to ensure that your app is isolated and secured from other running apps

Understanding status messages

When you issue the cf push CLI command you see a series of status messages. If you examine them carefully, you'll see the following sequential phases:

  1. Your push successfully uploaded the app source code to the staging area.
  2. If an existing instance of your app is already running, it's stopped before staging begins.
  3. The buildpack starts the staging process, which can include:
    1. Downloading and installing various system components
    2. Downloading and installing runtime tools (Node.js and npm, for example)
    3. Putting your app into place
    4. Setting up the environment
    5. Bundling everything up to create the droplet
    To speed up these steps, staging makes heavy use of cache, so you might also see some reuse-from-cache messages in the mix.
  4. The DEA tries to start your app from the droplet, running under supervision of a warden (container).

Quiz

Test your knowledge of what you've learned in this tutorial. Answers are below.

 

  1. You must install Node.js and npm on your computer before deploying a Node.js app to Bluemix.
    1. True
    2. False; you only need Node.js installed
    3. False; you only need npm installed
    4. False; you only need source code and the Cloud Foundry CLI
  2. The port at which Bluemix looks for your running app is:
    1. 8080
    2. 80
    3. Indicated by the PORT environment variable
    4. Dependent on the route
  3. The application name you choose for your Lauren's Lovely Landscape Bluemix deployment must be:
    1. Long and important sounding
    2. Short and concise
    3. Unique among all your other apps
    4. Unique among all apps at the same data center
    5. Unused by any other Bluemix users in the entire world
  4. How can you tell if your mocha unit tests have passed?
    1. The test-results message is in green
    2. The console messages tally all the unit tests passed
    3. You see a count of passed tests
    4. Any of a through c

Answers to quiz

1. d, 2. c, 3. e, 4. d

What's next?

In this tutorial, you:

  • Deployed a Node.js app, including an instance of the Express web server, to Bluemix using the Cloud Foundry CLI
  • Used an editor to examine and modify the app's code
  • Installed dependencies for your app using npm
  • Ran and tested your modified app on your local computer
  • Updated your deployed app on Bluemix via the Cloud Foundry CLI
  • Reviewed key Bluemix terminology and how to decipher status messages

Now, continue learning "Bluemix fundamentals" on developerWorks with this next tutorial. You'll learn how to set up team collaboration and automated deployments for your Node.js app:

More Bluemix resources

For a steady stream of tutorials and other technical resources to help you learn, develop, and connect with Bluemix, see the Bluemix page on developerWorks.


Downloadable resources


Related topics


Comments

Sign in or register to add and subscribe to comments.

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Cloud computing, Java development, Web development
ArticleID=1013070
ArticleTitle=Bluemix fundamentals: Deploy a sample Node.js application to the cloud
publish-date=10052015