Nodejitsu

Save time managing and deploying your node.js app. Code faster with jitsu and npm

node.js cloud server in three minutes

About the author

Name
Location
Worldwide
nodejitsu nodejitsu

A question that often comes up to me is: 'How do I get started with Node.js?' The first step is to setup your local developer environment, which is a little different depending on your platform of choice:

Installing npm and node-cloudservers

Once you've got that going it would be a good idea to install npm (the node package manager). I'm currently running a mix of OS X and Ubuntu; so if you're using Windows, just checkout the npm GitHub repository for more detailed install instructions.

  curl http://npmjs.org/install.sh | sudo sh

To work with the Rackspace CloudServers API we will be using a library that I've recently completed called node-cloudservers. Installing node-cloudservers is easy using npm:

  sudo npm install cloudservers

Creating a server with node-cloudservers

Ok, it's time to create our first server. If you haven't already done so, now would be a good time to create your Rackspace, account and get your username and api key.

var cloudservers = require('cloudservers'),  
    sys = require('sys');

function createServer(serverName, username, apiKey) {  
  var options = {
    name: serverName,
    image: 49, // Ubuntu 10.04 (Lucid Lynx)
    flavor: 1, // 256 server
  };

  cloudservers.setAuth({ username: username, apiKey: apiKey }, function () {
    cloudservers.createServer(options, function (err, server) {
      server.setWait({ status: 'ACTIVE' }, 5000, function () {
        // Our server is now built and active, so we can install node.js on it
        sys.puts('Your server ' + serverName + ' is now ready.');
        sys.puts('  IP Address: ' + server.addresses.public);
        sys.puts('  Root password: ' + server.adminPass);
      });
    });
  });
};

var args = process.argv.slice(2);  
var serverName = args[0];  
var username = args[1] || 'your-username';  
var apiKey = args[2] || 'your-api-key';

createServer(serverName, username, apiKey);  

The above code sample authenticates with Rackspace CloudServers, creates a server with the specified options, and then waits for that server to become active and then outputs the servers public IP address and root password to the console. If you're looking for more documentation about all of the api calls available through node-cloudservers, check out our GitHub repository. You can either update the file with your username / API key pair or enter it from the command line:

  $ node create-server.js my-server my-username my-api-key
  Your server test-server is now ready.
    IP Address: 1.2.3.4
    Root password: my-server12345

Installing Node.js programmatically

We will be installing node.js on a Ubuntu 10.04 (Lucid Lynx) server that we just programmatically created. Now that the server is active we will execute the following shell script programmatically to get node installed along with npm and startup a 'hello node' server on that instance using nohup:

apt-get update  
apt-get install git-core build-essential libssl-dev  
cd /usr/src  
git clone http://github.com/ry/node.git  
cd node  
./configure
make  
make install  
curl http://npmjs.org/install.sh | sh  
cd /usr/src  
git clone git://github.com/Marak/hellonode.git  
cd hellonode  
nohup node server.js  

The easiest way to do this is to just spawn the ssh process using node. Here is some rudimentary code to do this using the node.js Child Process API.

var spawn = require('child_process').spawn,  
     fs = require('fs'),
     sys = require('sys');

 function ssh(username, host, file) {
   fs.readFile(file, function (err, data) {
     if (err) throw err;

     var hasPassword = false;
     var commands = data.toString().split('\n').join(' && ');
     var ssh = spawn('ssh', ['-l' + username, host, commands]);

     ssh.on('exit', function (code, signal) {
       process.exit();
     });

     ssh.stdout.on('data', function (out) {
       process.stdout.write(out);
       if (!hasPassword) {
         var stdin = process.openStdin();
         stdin.on('data', function (chunk) {
           ssh.stdin.write(chunk);
         });
       }

       hasPassword = true;
     });

     ssh.stderr.on('data', function (err) {
       process.stdout.write(err);
     });  
   });
 };

 var args = process.argv.slice(2);
 sys.puts('Running commands from ' + args[1] + ' as root@' + args[0]);
 ssh('root', args[0], args[1]);

We will run the script passing the IP address and commands.sh file as command line arguments. Unfortunately, password prompts are not managed by stdin, so we cannot pipe the password to our child ssh process through node directly. What that means is that you will have to manually copy-and-paste your root password from the command line when prompted. The node script will behave just like the terminal, so if you get any interactive prompts, just respond to them. Here's a sample:

  $ node create-server.js
  Your server is now ready:
    IP Address: 1.2.3.4
    Root password: what-a-password
  $ node ssh.js 1.2.3.4 commands.sh
  Running commands from commands.sh as root@1.2.3.4
  (...)
  root@1.2.3.4's password: 
  (...)
  > hello world running on port 80

Verifying your server is running

Now that we've installed node on the server we've created and started up the 'hello node' server we need to verify that this server is running. This can be accomplished by visiting the IP address in the browser or simply curling it:

  curl http://1.2.3.4/
  hello, i know nodejitsu.

From here it might be prudent to shut-down your node server through a more traditional ssh client and get hacking with node!

  killall -9 node