Run Node.js app on Ubuntu Server using pm2

I work with Node.js and some other JavaScript technologies in last months. One important think is – how run ready application on production server? It wasn’t easy question, because earlier I used only development mode in IDE (with automatic rebuild and generation in background). After some research I found pm2 – great package to run Node.js application in background. With that manager we can start, stop or restart many applications. Let’s see how we can easily run Node.js app.

I based on Ubuntu Server, becuase I think it’s good option and with a lot of packages. First, we must install pm2. It’s available in npm – we must first install nodejs on Ubuntu. All required repositories are available in special Node.js PPA script:

// Install package required by some npm
sudo apt-get install build-essential

// Download node
curl -sL https://deb.nodesource.com/setup_8.x -o nodejs.sh

// Prepare repos and settings
sudo bash nodejs.sh

// Run Node.js
sudo apt-get install nodejs

Then we can install pm2 using npm:

sudo npm install -g pm2

And it’s all. We can now use pm2 to run Node.js apps:

// Start app
pm2 start myapp.js

// Restart
pm2 restart myapp

// Stop
pm2 stop myapp

// List all saved apps
pm2 list

It’s also a good option to add pm2 to startup:

pm2 startup systemd

Last step is to prepare Nginx virtual host for Node.js app. I created Nginx posts series, but about PHP. In this case we will use Node.js and it works in similar way – we just “redirect” requests from Nginx to localhost Node.js app. Nginx will be a proxy server between user and real app. Why not only Node.js? Because with Nginx, we can avoid use root privilages for port 80/443 for Node app. Also Nginx is much faster for static content. It’s a example virtual host config:

server {
    root /var/www;

    index index.html index.htm index.nginx-debian.html;
    server_name mydomain.com;

    gzip            on;
    gzip_types      text/plain application/xml text/css application/javascript;
    gzip_min_length 1000;

    location / {
        proxy_redirect off;
        proxy_set_header Host $host;
        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_cookie_domain localhost mydomain.com;
        proxy_read_timeout 2m;
        proxy_connect_timeout 2m;

        // Node app port
        proxy_pass http://127.0.0.1:8080;
    }
}

And it’s all. With that you can run Node.js app in background and in production.