18 Oct 2013

5 minutes nodeJs server setup

This is a walk-through of a quick nodeJs server setup. The "server" OS is Ubuntu but it's pretty much the same steps on any other linux OS.

  1. Install nodeJs

    This should be as easy as apt-get install nodejs. The default repo may have an old version of node though. To install the version 0.10.x, you need to add the chris-lea repository.

    1
    2
    
    $ [sudo] apt-get install software-properties-common python-software-properties python g++ make
    $ [sudo] add-apt-repository ppa:chris-lea/node.js

    ...then update and install nodejs

    1
    2
    
    $ [sudo] apt-get update
    $ [sudo] apt-get install nodejs

    Alternatively, just download the nodeJs source (via wget) and build it yourself.

  2. Install NPM

    NPM is the node package manager that helps you install node modules.

    1
    
    $ [sudo] apt-get install npm

  3. Create source directory

    Next we create the home directory for our source files. Let's assume /var/www.

    1
    2
    
    $ [sudo] mkdir /var/www/
    $ cd /var/www

  4. Install needed modules

    In the source directory, we install the needed node modules for our nodeJs application. Assuming, our app uses express and socket.io for example, we will have.

    1
    2
    
    $ [sudo] npm install express
    $ [sudo] npm install socket.io

  5. Install forever

    Forever keeps your node script running continuosly. This means, once you exit the terminal, your application will not terminate as expected of a command like node app.js

    1
    
    $ [sudo] npm install forever -g

    Note the -g (global mode) switch.

  6. Upload and start your application

    Upload your node application to the source directory you created (/var/www). I am assuming you have FTP setup already. If not, you can just use SFTP (add your server details to your fav FTP client and set the connection type/security to SFTP). Next, start your app via forever.

    1
    
    $ [sudo] forever start /var/www/app.js

Just by the way, if you need your application to listen on port 80, server.listen(80); won't work. There are a couple of ways to do this. the famous one is using nginx as a proxy. Except you need nginx for something else though, that's not necessary. You can do a simple port forwarding like this

1
$ [sudo] iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 3000

My name is Opeyemi Obembe. I build things for web and mobile. You should follow me on Twitter (@kehers).