CHAPTER 12

image

Debugging and Deploying Your Application

In this book you have seen a great deal of what you are capable of producing with Node.js. You have created an application, or you are envisioning an application that you will want to publish. This means you will need to become familiar with the process of deploying your code to several destinations for your code. In addition to deploying your code, you will revisit and expand on some of the debugging techniques from Chapter 7 when encountering the V8 debugging module.

There are several methods and platforms that are available to you as a Node.js developer that will allow you to deploy your code. In this chapter you will examine techniques that range from self-deployment on a machine that you own to deploying on a cloud-based platform as a service solution. You will also learn how to publish your modules to npm.

At the time of this writing there is an enormous variety in cloud-based platforms as service hosting solutions for your Node.js applications. This chapter is not a catalog of every possible hosting solution, but it looks at several common and practical methods you can utilize to host Node.js applications.

12-1. Logging Information to the Console

Problem

You need to be able to gather important information about your application by logging information to your console window.

Solution

The easiest way to log information to the command line when you are debugging your code is to use the console module that is native to Node.js. In this solution you see there are various methods that can be used to log data to the console by using this module as shown in Listing 12-1.

Listing 12-1.  Logging to the Console

/**
* Logging information to your console.
*/
 
console.time('timer'),
console.log('hey %s', 'there'),
console.info('info'),
console.warn('warn'),
console.error('error'),
console.dir(console);
console.trace(console.error('traced'));
console.assert(true !== false, 'true equals false'),
console.timeEnd('timer'),

How It Works

The console module relies on Node.js’s use of stdout and stderr. The console object in the Node.js source is created by accepting those two streams as arguments (see Listing 12-2).

Listing 12-2.  Instantiating the Console

function Console(stdout, stderr) {
  if (!(this instanceof Console)) {
    return new Console(stdout, stderr);
  }
  if (!stdout || !util.isFunction(stdout.write)) {
    throw new TypeError('Console expects a writable stream instance'),
  }
  if (!stderr) {
    stderr = stdout;
  }
  var prop = {
    writable: true,
    enumerable: false,
    configurable: true
  };
  prop.value = stdout;
  Object.defineProperty(this, '_stdout', prop);
  prop.value = stderr;
  Object.defineProperty(this, '_stderr', prop);
  prop.value = {};
  Object.defineProperty(this, '_times', prop);
 
  // bind the prototype functions to this Console instance
  Object.keys(Console.prototype).forEach(function(k) {
    this[k] = this[k].bind(this);
  }, this);
}

Once the object is instantiated, the stderr and stdout properties are converted to properties on the console object itself by using the Object.defineProperty() method.

In your solution, you utilized each of the core methods that are exposed on the console object. First, and most common, is the console.log() method. This method accepts any number of arguments, formats them together using the util module as shown in Listing 12-3, and writes the result to stdout. The console.info method is the same as the console.log method and formats the arguments in the same way.

Listing 12-3.  Console.log as a stdout.write

Console.prototype.log = function() {
  this._stdout.write(util.format.apply(this, arguments) + ' '),
};
 
Console.prototype.info = Console.prototype.log;

The next console method you will encounter is the console.error() method. This is the same as the console.warn() method. These methods are similar to the console.log() and console.info() methods with the difference being that they write to the stderr instead of stdout, as shown in Listing 12-4.

Listing 12-4.  Console.error and console.warn

Console.prototype.warn = function() {
  this._stderr.write(util.format.apply(this, arguments) + ' '),
};
 
Console.prototype.error = Console.prototype.warn;

Next you utilize the console.dir() method. This function uses the util.inspect() method to describe the object that is passed to it (see Listing 12-5). In this case you inspect the console object itself.

Listing 12-5.  Console.dir()

Console.prototype.dir = function(object) {
  this._stdout.write(util.inspect(object, { customInspect: false }) + ' '),
};

The output of the console.dir(console); call is shown in Listing 12-6.

Listing 12-6.  Console.dir(console);

{ log: [Function],
  info: [Function],
  warn: [Function],
  error: [Function],
  dir: [Function],
  time: [Function],
  timeEnd: [Function],
  trace: [Function],
  assert: [Function],
  Console: [Function: Console] }

Next, ran console.trace() to log any error to stderr a stack trace. This method’s source is shown in Listing 12-7. You can see that the error is logged via the console.error() method once the name has been changed to demonstrate that it is a ‘Trace’;.

Listing 12-7.  Console.trace() Source

Console.prototype.trace = function() {
  // TODO probably can to do this better with V8's debug object once that is
  // exposed.
  var err = new Error;
  err.name = 'Trace';
  err.message = util.format.apply(this, arguments);
  Error.captureStackTrace(err, arguments.callee);
  this.error(err.stack);
};

The final console method that you will use is the console.assert() method. This method leverages the assert module to log the results of the assert.ok() method. You can see how this works internally in Listing 12-8.

Listing 12-8.  Console.assert()

Console.prototype.assert = function(expression) {
  if (!expression) {
    var arr = Array.prototype.slice.call(arguments, 1);
    require('assert').ok(false, util.format.apply(this, arr));
  }
};

12-2. Using a Graphical Debugging Tool

Problem

You would like to utilize a tool that will allow you to debug your Node.js application in an integrated development environment (IDE)-like debugging tool. This means you want to have graphical access to your Node.js debugging environment.

Solution

One of the most basic yet most consistent cross-platform debugging tools for Node.js applications is an npm package called node-inspector. This package is used to bind the debugger that comes with a Blink-based browser, such as Google Chrome or the latest versions of Opera. You will then gain access to the native debugging tools for these browsers but it will allow you to navigate the code and debug your Node.js application in an IDE-like setting.

To get started with node-inspector, install it globally via npm. This gains you access to the node-inspector command that will allow you to start the debugger listening from any directory on your machine, as shown in Listing 12-9.

Listing 12-9.  Node-inspector Install and Implementation

$ npm install -g node-inspector
 
$ node-inspector
Node Inspector v0.3.1
   info  - socket.io started
Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.

Once the inspector is running, you can begin a new instance of your Node.js application. For this example assume that a simple HTTP server responds with the text “hello world”.  When you start this Node.js application you need to enable the debugging hooks by passing the parameter –debug to the command. This looks like what you see in Listing 12-10.

Listing 12-10.  Beginning Node Inspection by Creating a Server

$ node --debug 12-2-1.js
debugger listening on port 5858

How It Works

Now that you have a debugger listening on the proper port and the inspector is running, you can experience the fun of using a graphical debugger by navigating to http://127.0.0.1:8080/debug?port=5858. This is where the node-inspector has Blink developer tools opened and will allow you to debug your code. This initial interface will look similar to that shown in Figure 12-1.

9781430260585_Fig12-01.jpg

Figure 12-1. node-inspector initial state

From here you now have the ability to open up the Sources panel and view the source files that are available to you. This is shown in Figure 12-2; you can select the file you wish to debug.

9781430260585_Fig12-02.jpg

Figure 12-2. Sources panel in node-inspector

Once you have selected your file, you can now see the entire source that is running for that file in Node.js. Figure 12-3 shows how you have created a breakpoint and are debugging the Node.js application. This has broken at that point and the inspector has provided you with the call stack and scope variables and other important information that can be accessed through the debugger interface.

9781430260585_Fig12-03.jpg

Figure 12-3. node-inspector viewing a source file

Finally, node-inspector also gives you access to more detail about objects in your source code by providing hover-over information. This information gives you more detail about the object that is being inspected (see Figure 12-4).

9781430260585_Fig12-04.jpg

Figure 12-4. Hovering over an object with node-inspector

12-3. Debugging Your Application in a Production Environment

Problem

You have a Node.js application running on a production server that is behaving in a manner that prompts you to step into the code and see what is happening. You need to be able to attach a debugger to the production process in order to debug your application.

Solution

Connecting to a Node.js process that is currently running is built into the Node.js debugging functionality. This will attach the V8 debugger to your application in the same way that starting your application with the debug flag will.

You first need to run a Node.js process. For this example you can start a simple HTTP server that you created for debugging in Section 12-2. Once you have this running, you need to find the process identifier on your operating system that is running this Node.js process. You can do this through an activity monitor, task manager on Windows, or the shell using grep - $ ps ax | grep node.

Once you have the process identifier, you can then tell the debugger to connect to the process, as shown in Listing 12-11.

Listing 12-11.  Connecting the Debugger to a Node.js Process

$ node debug -p 6284
connecting... ok
debug>

You now have the V8 debugger prompt, which is connected to your Node.js process (shown on your original command line as shown in Listing 12-12).

Listing 12-12.  Debugger Connected

$ node 12-2-1.js
Starting debugger agent.
debugger listening on port 5858

Once you are connected to the process, from the debug> prompt you might like to know at what point in the process the current state of your application resides. You can do this by either pausing the application using debug> pause or by processing a step into debug> s or the next debug> n.

You can now debug your application on production, to pinpoint where you are encountering issues in your application.

How It Works

Debugging using the Node.js debugger was covered in detail in Chapter 7, and using the command $ node debug –p <pid> to bind to a Node.js process will give you access to the same commands that you saw in Chapter 7. This is the V8 debugger that runs the debug terminal.

When you begin debugging, as mentioned above, you are able to see where you are at in the code by typing debug> n (see Listing 12-13).

Listing 12-13.  The Next Step in V8 Debugger

connecting... ok
debug> n
break in net.js:1153
 1151
 1152 function onconnection(clientHandle) {
 1153   var handle = this;
 1154   var self = handle.owner;
 1155

This listing is just an example of where you may find yourself in the code. In your case you may be anywhere inside of your application or the modules that are imported to your application. You can then continue to execute your program by typing debug> c, as shown in Listing 12-14. This example shows that by continuing you were able to run the code until it encountered the debugger; command. This command tells the V8 debugger to stop executing and to wait.

Listing 12-14.  Continue to Debugger

debug> c
break in c:UserscgackenheimerDropboxookcode1212-2-1.js:7
  5
  6 var server = http.createServer(function(req, res) {
  7     debugger;
  8     res.end('hello world'),
  9 });

You are now able to debug your application and you did not need to start Node.js with the debug command passed to it. You only needed to find the process that was running and bind the V8 debugger to the application by using the process identifier.

12-4. Continuously Running Your Server with Forever

Problem

You want to ensure that your Node.js process will continuously run and be able to restart after unexpected failures on your production machine.

Solution

To keep a Node.js process running, there are several choices that you have as a developer for doing so. In this solution you will examine how to utilize the forever module to keep your processes alive and running continuously.

To get started you must first install the forever module. The module source is located athttps://github.com/nodejitsu/forever and can be installed as a global command-line module, as shown in Listing 12-15.

Listing 12-15.  Installing forever

$ npm install -g forever

Once you have forever installed from the command line, you are now able to run your Node.js process utilizing the command-line interface (CLI). In order to start your Node.js process utilizing the forever module, you must start the script by using the forever start command, as shown in Listing 12-16.

Listing 12-16.  forever start

$ forever start app.js
warn:    --minUptime not set. Defaulting to: 1000ms
warn:    --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info:    Forever processing file: app.js

You can then check to see the status of any running applications that forever is serving by using the forever list command (see Listing 12-17).

Listing 12-17.  forever list

$ forever list
info:    No forever processes running
 
# Once a task is running.
 
$ forever list
info:    Forever processes running
data:        uid  command             script    forever pid   logfile                       uptime
data:    [0] UJVS /usr/local/bin/node 12-2-1.js 41659   41660 /Users/gack/.forever/UJVS.log 0:0:2:46.801
data:    [1] VVX7 /usr/local/bin/node app.js 41757   41758 /Users/gack/.forever/VVX7.log 0:0:0:3.444

You may have noticed some warnings that state you have not specified spinSleepTime or minUptime forever options. To set these flags, they must be set before you tell forever to start. This will look like the example shown in Listing 12-18, in which you specify a minimum uptime and spin sleeptime of 20 milliseconds each.

Listing 12-18.  Setting forever Flags

$ forever --minUptime 10 --spinSleepTime 10 start app.js
info:    Forever processing file: app.js

How It Works

Forever is a Node.js module that ensures that the script you have told it to execute will run continuously. When you start an application with forever, you are actually creating a monitor instance that will attempt to spawn your script as a child process. It does this so that forever will be able to monitor the process of the child and restart the process if the child is interrupted. The process of starting the monitor is shown in Listing 12-19, which is the forever source for the monitor.

Listing 12-19.  Starting a forever Monitor

Monitor.prototype.start = function (restart) {
  var self = this,
      child;
 
  if (this.running && !restart) {
    process.nextTick(function () {
      self.emit('error', new Error('Cannot start process that is already running.'));
    });
    return this;
  }
 
  child = this.trySpawn();
  if (!child) {
    process.nextTick(function () {
      self.emit('error', new Error('Target script does not exist: ' + self.args[0]));
    });
    return this;
  }
 
  this.ctime = Date.now();
  this.child = child;
  this.running = true;
  process.nextTick(function () {
    self.emit(restart ? 'restart' : 'start', self, self.data);
  });
 
  function onMessage(msg) {
    self.emit('message', msg);
  }
 
  // Re-emit messages from the child process
  this.child.on('message', onMessage);
 
  child.on('exit', function (code, signal) {
    var spinning = Date.now() - self.ctime < self.minUptime;
    child.removeListener('message', onMessage);
    self.emit('exit:code', code, signal);
 
    function letChildDie() {
      self.running = false;
      self.forceStop = false;
      self.emit('exit', self, spinning);
    }
 
    function restartChild() {
      self.forceRestart = false;
      process.nextTick(function () {
        self.start(true);
      });
    }
 
    self.times++;
 
    if (self.forceStop || (self.times >= self.max && !self.forceRestart)
      || (spinning && typeof self.spinSleepTime !== 'number') && !self.forceRestart) {
      letChildDie();
    }
    else if (spinning) {
      setTimeout(restartChild, self.spinSleepTime);
    }
    else {
      restartChild();
    }
  });
 
  return this;
};

Once the child process has started, an event listener is bound to the process, listening for events. When the ‘exit’ event is emitted, forever will check to see if the process is spinning and then restart the process. This is the foundation of forever: catching exiting processes and restarting them continuously.

As you built your solution you were able to see a few of the parameters that are used to manipulate the way in which forever executes. The full list of available parameters and options that can be used with forever is shown in Table 12-1.

Table 12-1. Options and Parameters for the forever Module

Name Type Description
Cleanlogs Action Deletes all forever log files.
Clear <key> Action Remotes the set key.
Columns add <col> Action Adds the specified column to the forever list output.
Columns rm <col> Action Removes the specified column from the forever list output.
Columns set <col> Action Set all columns for the forever list output.
Start Action Starts a Node.js script.
Config Action Lists all forever configurations.
List Action Lists all running processes.
Logs Action Lists the log files for all the forever processes.
Logs <script|index> Action Lists the log file for the specified script or index.
Restart Action Restarts a script.
Restartall Action Restarts all scripts.
Set <key> <val> Action Sets an option specified by the key and the value.
Stop Action Stops the script execution.
Stopall Action Stops all the forever scripts.
-a –append Option Appends the logs.
-c Command Option This is the command to be executed—this defaults to ‘node’.
-d, --debug Option Log debug output.
-e ERRFILE Option Specifies a named error file.
-f –fifo Option Stream logs to stdout.
-h, --help Option Shows help.
-l LOGFILE Option Specifies a named log file.
-m  MAX Option Runs the script for only a maximum number of times.
-o OUTFILE Option Specifies a named out file.
-p PATH Option Specifies the log file path.
-s, --silent Option Silences stdout and stderr on the child script.
-v,  --verbose Option Turns on verbose messages from forever.
-w, --watch Option Watches for file changes, restarting if detected.
--minUptime Option Sets the minimum uptime in milliseconds that the script is considered “spinning.”
--pidFILE Option Lists the pid file.
--plain Option Disables command-line coloring.
--sourceDir Option Lists the source directory that the SCRIPT is relative to.
--spinSleepTime Option Lists the time in milliseconds to wait between launches of the “spinning” script.
--watchDirectory Option Lists the top-level watch directory.

12-5. Deploying Your Application on Your Own Server

Problem

You have a server that you have dedicated to hosting your Node.js application and you need to be able to deploy your application to that server.

Solution

Deploying your application to your own server requires a few steps to happen. To do this, you can manually copy the files over to your destination server, install the npm dependencies, and start the script, but there are more automated ways for doing this (as you can see in Listing 12-20). This solution will utilize a Git process to install dependencies and start your Node.js application.

Listing 12-20.  Deploying with Git

## Initialize the repository
$ git init
## add your files
$ git add .
## make a change to your source on the development machine
$ git commit –am “I made an important change”
$ git push origin

This will push the changes to the Git repository that is located on your remote production machine and it will then use a Git post-receive hook to install dependencies and start your Node.js application.

How It Works

The key to this process is the nature of Git’s post-receive hooks. This will execute a bash script each time that a change is received in the repository. To get started you need to build a post-receive file in the ‘hooks’ directory of your production Git repository. A basic deploy script would look like the one shown in Listing 12-21.

Listing 12-21.  Basic repo.git/hooks/post-receive File

#!/bin/sh
echo "processing post receive hook"
echo "installing npm dependencies"
npm install
echo "starting application"
node app.js

This will utilize the package.json file that is part of your repository, and it will utilize npm to install any dependencies that your code requires. After these are installed it will begin the node process by running the node app.js command. However, as you saw in the previous section, you may want to accommodate for failures and run this script by using forever. Assuming that you have already installed forever on your production machine globally, you can alter your script to look like what is shown in Listing 12-22.

Listing 12-22.  Post-receive Hook Using forever

#!/bin/sh
echo "processing post receive hook"
forever stop app.js
echo "installing npm dependencies"
npm install
echo "starting application"
forever start app.js

image Note  Running your post-receive hook in this manner will stop your server for the entirety of your npm install. In a volatile production environment it is best to segregate these events so that you do not limit production uptime.

By using the post-receive hooks you can deploy your code as you would normally, targeting a production repository, and then have Git initialize the build-and-deploy process on the target machine.

12-6. Publishing Your Code to npm

Problem

You have built a Node.js module that you would like to share with the greater Node.js community. In order to do this you will want to deploy your module to npm.

Solution

With npm, it is simple to create and publish a module to the registry. To do this, you simply use the npm publish command shown in Listing 12-23.

Listing 12-23.  Publishing to npm

$ npm publish /path/to/your/module

How It Works

This solution works by leveraging the npm command-line tool. This will read the directory that you have specified, which alternatively could be a tarball of the module. Once this is read, it will read the package.json file that is associated with the file and determine if the module is eligible for publication. The name and the version of the package must be unique or the publication will fail.

Once it is determined that the publication is allowed, the package will be added to the npm registry and will be discoverable by Node.js developers everywhere.

12-7. Using Amazon Web Services to Host Your Application

Problem

You want to deploy your Node.js application to be hosted on the Amazon Web Services (AWS) hosting platform.

Solution

For deploying to AWS, you first need to create an AWS account found at http://aws.amazon.com. From there you can then create an Elastic Compute Cloud (EC2) instance; in this solution Ubuntu Server 12.04 was utilized. Once you have your EC2 instance provisioned you can then connect with Secure Shell (SSH) into that instance by using the key pair that you downloaded when you created the instance.

If you are planning to host a web application on your EC2 instance, you need to ensure that the “Security Group” which the EC2 instance is utilizing has opened port 80 so that the web content can be served.

Once you are remotely connected to your Ubuntu instance, you will want to install Node.js. You can use the Ubuntu package by Chris Lea for this, or you can install from the source shown in Listing 12-24. Once you have Node.js and npm installed, then the next step is to get your source code to the remote server on AWS.

Listing 12-24.  Installing node.js

$ sudo apt-get update
$ sudo apt-get install build-essential libssl-dev
$ git clonehttps://github.com/joyent/node.git
$ ./configure
$ make
$ sudo make install

Now that you have Node.js installed, you can run a simple web application by running a node app with an HTTP server bound on port 80, $ sudo node app.js. However, you likely will have code from another location you would like to serve from the server.  There are several ways that you can do this, but it has become increasingly popular to utilize a GitHub or other Git repository in order to transfer your code to your server. Again, simply clone this repository, ensure that you have the source configured to listen on port 80, and you can start your Node.js application on the server.

This can also work the other way, just as you saw in Section 12-5, where you can create a production Git repository on your EC2 instance with a post-receive hook installed and you will be able to deploy directly to that repository from your local development environment.

How It Works

Utilizing the AWS EC2 works because it provisions a virtual instance of a real Ubuntu server. This means that you are able to run everything that you would on a typical Ubuntu server (or another type of EC2 server instance) installation; thus you are able to run Node.js. EC2 provides you with granular control over security and provisioning for your server so that you can tell it to open port 80 and provision new instances with the click of a button.

Once you have Node.js installed, you are able to run a Node.js application as you would as if you were running it locally. To run a Node.js application on port 80 by using Ubuntu server does require an elevated privilege, which is why you needed to utilize the sudo command to start your application. If you had omitted this and still attempted to run on port 80, you would have encountered an error like the one shown in Listing 12-25.

Listing 12-25.  Requiring Elevated Permissions for Port 80

ubuntu@ip:∼/test$ node app.js
 
events.js:80
        throw er; // Unhandled 'error' event
              ^
Error: listen EACCES
    at exports._errnoException (util.js:676:11)
    at Server._listen2 (net.js:1051:19)
    at listen (net.js:1093:10)
    at Server.listen (net.js:1168:5)
    at Object.<anonymous> (/home/ubuntu/test/app.js:7:8)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:349:32)
    at Function.Module._load (module.js:305:12)
    at Function.Module.runMain (module.js:490:10)
ubuntu@ip:∼/test$ sudo node app.js

12-8. Deploying Your Application Using Heroku

Problem

There are several solutions that represent platforms that you as a developer are able to utilize to deploy your code to the cloud. One of these that allows for Node.js applications is Heroku. You would like to be able to install your application to the Heroku platform as a service.

Solution

To install your Node.js application to the Heroku platform, there are essentially two steps: install the Heroku command-line tools (known as the toolbelt), and then push your code to Heroku for deployment.

In order to get started, you must first download the Heroku toolbelt from the Heroku web site,https://toolbelt.heroku.com, shown in Figure 12-5.

9781430260585_Fig12-05.jpg

Figure 12-5. Heroku toolbelt download page

Once you have downloaded the toolbelt, you must now sign in to Heroku by using the CLI. Now would be a good time to create a Heroku account online if you have not yet done so. You can sign on to Heroku by using the toolbelt CLI, as shown in Listing 12-26.

Listing 12-26.  Heroku Login

> heroku login
Enter your Heroku credentials.
Email: [email protected]
Password (typing will be hidden):
Authentication successful.

Next, you can go about the business of developing your Node.js application as you normally would, ensuring that dependencies are listed in your package.json file associated with the application. The subtle differences occur when you are preparing to test and deploy your application with Heroku.

When you deploy a Node.js application to Heroku, you must first create a file, called Procfile, in the root of your application. This file will tell Heroku the type of application process that you are attempting to create. In the case of a Node.js application you will generate a Procfile that will tell Heroku you intend to create a web application and the node <script> target that will be the entry for your application (see Listing 12-27).

Listing 12-27.  A Node.js Procfile for Heroku

web: node server.js

You can now test your application utilizing Heroku’s testing service called Foreman. This happens when you type $ foreman start in the directory that houses your Procfile. This will create a local web instance of your application running on port 5000 by default, allowing you to test your application before you deploy.

After testing is completed, you can deploy your application to the Heroku platform. This is done by first storing the application into a Git repository, if it is not already present in one. This Git repository is then associated with a Heroku origin with the command $ heroku create. This will generate a creative and unique URL for your application, and it will add a remote of Heroku to the Git repository. The Heroku remote will be the target of your deployment pushes. Once you have successfully committed your changes, you can push them to the Heroku remote and the deploy will automatically commence, showing you stdout of the process as it occurs, as shown in Listing 12-28.

Listing 12-28.  Abridged Deploy Output

$ git push heroku master
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 361 bytes | 0 bytes/s, done.
Total 4 (delta 3), reused 0 (delta 0)
 
-----> Node.js app detected
-----> Resolving engine versions
       Using Node.js version: 0.8.21
       Using npm version: 1.1.65
-----> Fetching Node.js binaries
-----> Vendoring node into slug
-----> Installing dependencies with npm
       Dependencies installed
-----> Building runtime environment
-----> Discovering process types
       Procfile declares types -> app, restart
 
-----> Compiled slug size: 35.7MB
-----> Launching... done, v122
       http:// yourrepo.herokuapp.com yourrepo.herokuapp.com deployed to Heroku
 
To [email protected]:yourrepo.git
   Sha...hash  master -> master

You will not only be able to view your application on the web, but the Heroku web interface will also give you an insight into the state of your application (see Figure 12-6).

9781430260585_Fig12-06.jpg

Figure 12-6. Heroku dashboard

How It Works

Heroku deployment for Node.js works by leveraging Git to deploy code to the appropriate technology stack in the Heroku platform.

When you first generate your Procfile, which tells Heroku which process you want to run your Node.js under, you tell it to use the web type. This means that the web stack and web-routing processes will be utilized in order to generate and run your application.

Heroku will also, during the deploy process, automatically detect a Node.js application and know that it will ensure that the prescribed versions of Node.js and npm are installed and utilized. It will then parse your package.json file and install the listed dependencies before attempting to run your application. You now have your application running on the Heroku platform.

12-9. Deploying Your Application to Nodejitsu

Problem

You want to utilize Nodejitsu in order to host your Node.js application on the cloud.

Solution

To start deploying your Node.js application with Nodejitsu, you must first create a Nodejitsu account athttps://www.nodejitsu.com/signup/. Once you have an account, install the command-line tools that are utilized to deploy your Node.js application to the cloud.

To install the CLI for Nodejitsu, use npm and install it globally, as shown in Listing 12-29.

Listing 12-29.  Installing the Jitsu CLI

$ npm install -g jitsu

This will then give you access to all of the features of the Nodejitsu command line. You can see what commands are available to you by typing $ jitsu, which will output all of the help documentation, as you can see in Listing 12-30.

Listing 12-30.  $ jitsu Options

$ jitsu
info:    Welcome to Nodejitsu cgack
info:    jitsu v0.13.0, node v0.10.17
info:    It worked if it ends with Nodejitsu ok
info:    Executing command
help:              ___  __
help:        /  /  /   /_  /  /
help:     __/  /  /   __/ /__/
help:
help:    Flawless deployment of Node.js apps to the cloud
help:    open-source and fully customizable.
help:    https://github.com/nodejitsu/jitsu
help:
help:    Usage:
help:
help:      jitsu <resource> <action> <param1> <param2> ...
help:
help:    Common Commands:
help:
help:    To sign up for Nodejitsu
help:      jitsu signup
help:
help:    To log into Nodejitsu
help:      jitsu login
help:
help:    To install a pre-built application
help:      jitsu install
help:
help:    Deploys current path to Nodejitsu
help:      jitsu deploy
help:
help:    Lists all applications for the current user
help:      jitsu list
help:
help:    Additional Commands
help:      jitsu apps
help:      jitsu cloud
help:      jitsu logs
help:      jitsu env
help:      jitsu conf
help:      jitsu users
help:      jitsu databases
help:      jitsu snapshots
help:      jitsu tokens
help:      jitsu logout
help:
help:    Options:
help:  --version, -v   print jitsu version and exit                                                       [string]
help:  --localconf     search for .jitsuconf file in ./ and then parent directories                       [string]
help:  --jitsuconf, -j  specify file to load configuration from                                            [string]
help:  --noanalyze     skip require-analyzer: do not attempt to dynamically detect dependencies  [boolean]
help:  --colors        --no-colors will disable output coloring                           [boolean]  [default: true]
help:  --confirm, -c   prevents jitsu from asking before overwriting/removing things        [boolean]  [default: false]
help:  --release, -r   specify release version number or semantic increment (build, patch, minor, major)  [string]
help:  --raw           jitsu will only output line-delimited raw JSON (useful for piping)  [boolean]
info:    Nodejitsu ok

You now need to log in to your Jitsu account by using the $ jitsu users login command (see Listing 12-31).

Listing 12-31.  Jitsu Login

$ jitsu users login
info:    Welcome to Nodejitsu
info:    jitsu v0.13.0, node v0.10.17
info:    It worked if it ends with Nodejitsu ok
info:    Executing command users login
help:    An activated nodejitsu account is required to login
help:    To create a new account use the jitsu signup command
prompt: username:  you
prompt: password:
info:    Authenticated as you
info:    Nodejitsu ok

At this point, you can create a Nodejitsu application from your Node.js source by navigating to that source directory and using the command $ jitsu deploy. This will then prompt you for a subdomain, a start script, the version you wish to name this deploy as, and the Node.js engine version you require to run. The subdomain will then be how you identify your application. To see a list of running applications once you have deployed a Jitsu app, use the jitsu apps list command, as shown in Listing 12-32.

Listing 12-32.  Listing Nodejitsu Applications

$ jitsu apps list
info:    Welcome to Nodejitsu cgack
info:    jitsu v0.13.0, node v0.10.17
info:    It worked if it ends with Nodejitsu ok
info:    Executing command apps list
info:    Listing all apps for user
data:    name    state   subdomain drones running snapshot
data:    wizards stopped wizards       0/1    user-wizards-0.0.1-4.tgz
data:    wsserv  stopped wsserv     0/1    user-wsserv-0.0.1-7.tgz
info:    Nodejitsu ok

How It Works

By using the Jitsu command line, you can deploy code to the Nodejitsu cloud platform with simple commands. This happens because Nodejitsu knows and expects a Node.js application to be deployed to the platform. When you run jitsu deploy on your source it will provision a virtual server that will host your subdomain on the server, allowing you to run your Node.js application in the cloud.

Similar to the Heroku CLI, Jitsu allows you to manage your applications and your account fully from the command line. This means that you can start, stop, restart, view, and create applications with the command line, as you can see from Listing 12-33, which outlines the Jitsu apps * procedures available.

Listing 12-33.  Jitsu apps*

$ jitsu apps
info:    Welcome to Nodejitsu cgack
info:    jitsu v0.13.0, node v0.10.17
info:    It worked if it ends with Nodejitsu ok
info:    Executing command apps
help:    The `jitsu apps` command manages
help:    Applications on Nodejitsu. Valid commands are:
help:
help:    jitsu apps deploy
help:    jitsu apps list
help:    jitsu apps create
help:    jitsu apps cloud   [<name>]
help:    jitsu apps view    [<name>]
help:    jitsu apps update  [<name>]
help:    jitsu apps destroy [<name>]
help:    jitsu apps start   [<name>]
help:    jitsu apps restart [<name>]
help:    jitsu apps stop    [<name>]
help:    jitsu apps setdrones [<name>] <number>
help:
help:    For commands that take a <name> parameter, if no parameter
help:    is supplied, jitsu will attempt to read the package.json
help:    from the current directory.
help:
help:    Options:
help:      --version, -v    print jitsu version and exit                                                       [string]
help:      --localconf      search for .jitsuconf file in ./ and then parent directories                       [string]
help:      --jitsuconf, -j  specify file to load configuration from                                            [string]
help:      --noanalyze      skip require-analyzer: do not attempt to dynamically detect dependencies           [boolean]
help:      --colors         --no-colors will disable output coloring                                           [boolean]  [default: true]
help:      --confirm, -c    prevents jitsu from asking before overwriting/removing things                      [boolean]  [default: false]
help:      --release, -r    specify release version number or semantic increment (build, patch, minor, major)  [string]
help:      --raw            jitsu will only output line-delimited raw JSON (useful for piping)                 [boolean]
info:    Nodejitsu ok

12-10. Deploying to Windows Azure

Problem

You want to utilize the Windows Azure cloud platform to deploy your Node.js solution.

Solution

When Node.js was first created, running Node on Windows was an afterthought. Today Windows has become a first-class citizen in the Node.js realm and as such Microsoft has devoted a great deal of time and effort to making deploying Node.js code and managing it on their cloud platform—Azure—easy and accessible to developers.

To get started with Node.js and Azure, you must first create an account. Sign in to the Azure management portal found athttps://manage.windowsazure.com. Once you have signed in, you can create a new web site. Click on the large “+ New” button and then select “web site.” You will then name your subdomain and select a region before creating your web site. This process is shown in Figure 12-7.

9781430260585_Fig12-07.jpg

Figure 12-7. Creating an Azure web site for your Node.js application

From here, one of the easiest ways to get a Node.js application created is to go to the dashboard for your newly created application and select the “Set up deployment from source control” option. This option will then present you with the ability to choose any location in which you have stored your application source as source control, which will look similar to Figure 12-8.

9781430260585_Fig12-08.jpg

Figure 12-8. Source of the application in Azure

From there you can choose your repository. Azure will grab the source and dependencies and deploy the application directly, which will then show on your application’s “Deployments” dashboard (see Figure 12-9).

9781430260585_Fig12-09.jpg

Figure 12-9. Application deployed

How It Works

Deploying to Windows Azure is similar to the other deployment methods that have been covered in this chapter. The source code will be located via a source control URL, which will then be uploaded to the platform in the cloud. The dependencies will then be installed and the application will start.

Windows Azure does this through a rich web portal that allows for viewing the data and interactions in real-time via the web as opposed to the previous solutions, which had portals, but most of the interaction that you saw was based in the command line.

One thing that you can do with your Azure instance is to quickly go online to monitor the status of your application and the resources that it is utilizing. This interface looks similar to that shown in Figure 12-10.

9781430260585_Fig12-10.jpg

Figure 12-10. Window Azure monitoring

From the bottom panel of the interface, you can start, stop, and restart your Node.js application with the push of a button, as shown in Figure 12-11.

9781430260585_Fig12-11.jpg

Figure 12-11. Start, stop, and restart your Azure application

Once you are running your application, you will also want to be able to publish changes to that application quickly. These deployments can be controlled via Azure Git URLs. To find and configure which URLs will control your future deployments, navigate to the Configure section of the Azure web portal for your application, as shown in Figure 12-12.

9781430260585_Fig12-12.jpg

Figure 12-12. Configure deployment URLs for your Azure Node.js application

You now have your Node.js application running on the Microsoft Windows Azure cloud. While this solution is slightly different than the previous cloud-hosting platforms that you have seen, you have seen that all of the platforms in this chapter can be wonderful resources for deploying your Node.js applications to the web quickly and efficiently on a web-based platform as a service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.5.86