Last Updated: February 25, 2016
·
8.629K
· bahaagalal

Install & Configure Node.JS & Nginx on Ubuntu

Step by Step Guide on how to install & configure Node.JS & Nginx on Ubuntu Server to start serving your web apps.

Step 1: Start off by updating your apt-get packages

sudo apt-get update

Step 2: Install all required packages to build and compile node from the source

sudo apt-get install g++ curl libssl-dev apache2-utils build-essential

Step 3: Download the latest version of node

sudo wget http://nodejs.org/dist/v0.10.30/node-v0.10.30.tar.gz

Step 4: Unpack the tar zipped file

sudo tar -xzf node-v0.10.30.tar.gz

Step 5: Change working directory to the unpacked folder and proceed to build the source code

cd node-v0.10.30
sudo ./configure
sudo make
sudo make install

Step 6: Install nginx form its apt-get package

sudo apt-get install nginx

Step 7: Create a directory for your app (get your app code into that directory)

sudo mkdir -p /var/www/mynodeapp

Step 8: Create an upstart script for your app (to automatically start your node app server)

sudo nano /etc/init/mynodeapp.conf

Copy the following code into your upstart script (don't forget to change the "server.js" in the last line to the name of the script file that starts your node server)

#!upstart
author "me"
description "mynodeapp"
setuid "ubuntu"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn
console log
env NODE_ENV=production
exec /usr/local/bin/node /var/www/mynodeapp/server.js

Step 9: Start your upstart script

sudo start mynodeapp

Step 10: Configure nginx to serve requests to your domain through the server behind your upstart script

sudo nano /etc/nginx/sites-enabled/mynodeapp

Copy the following code into the file (don't forget to change the port number in line 2 if your Node.JS app server is listening on another port)

upstream mynodeapp {
    server 127.0.0.1:3000;
        keepalive 64;
}

server {
        listen 80;
        server_name .myawsomedomian.com;
        access_log /var/log/nginx/mynodeapp.log;

        location / {
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;                             
                proxy_set_header Host $http_host;
                proxy_set_header X-NginX-Proxy true;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_pass http://mynodeapp/;
                proxy_redirect off;
                proxy_http_version 1.1;
        }
}

Step 11: Restart nginx

sudo service nginx restart

All is done. Congratulations your Node.JS app is now live and you can access it by visiting your domain.