Pagepro Blog

node.js

Setting up node.js application on Digital Ocean Droplet

Posted on .

Setting up node.js application on Digital Ocean Droplet

Introduction

Install node

Please avoid to install Node.js with apt-get on Ubuntu. If you already installed Node.js with the built in package manager, please remove that:

sudo apt-get purge nodejs && sudo apt-get autoremove && sudo apt-get autoclean

Install nvm

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash
$ nvm list
$ nvm ls-remote
$ nvm install 5.7.0
$ nvm use 5.7.0
$ nvm alias default 5.7.0
$ node -v

node -v should return: v5.7.0

Install npm globally:

$ npm install -g npm
$ npm -v

Check the npm version using npm -v to verify if it’s installed.

Install pm2

npm install -g pm2

Run example script to check if server is working

Create file for example server:

vim hello.js

Paste the code:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, 'localhost');
console.log('Server running at http://localhost:3000/');

Run the script with pm2:

pm2 start hello.js

Check if application is working:

curl http://localhost:3000

It should print: Hello World.

Set Up Nginx as a Reverse Proxy Server

Now that your application is running, and listening on localhost, you need to set up a way for your users to access it. We will set up an Nginx web server as a reverse proxy for this purpose. This tutorial will set up an Nginx server from scratch. If you already have an Nginx server setup, you can just copy the location block into the server block of your choice (make sure the location does not conflict with any of your web server’s existing content).

First, install Nginx using apt-get:

apt-get install nginx

Now open the default server block configuration file for editing:

vim /etc/nginx/sites-available/default

Delete everything in the file and insert the following configuration. Be sure to substitute your own domain name or IP address for the server_name directive. Additionally, change the port (3000) if your application is set to listen on a different port:

server {
    listen 80;

    server_name 138.68.128.12;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Make sure you didn’t introduce any syntax errors by typing:

nginx -t

Next, restart Nginx:

systemctl restart nginx

Next, permit traffic to Nginx through the firewall, if you have it enabled:

ufw allow 'Nginx Full'

Now the server should be running and be accessible in the browser.

Chris Lojniewski

Chris Lojniewski

http://pagepro.co

There are no comments.
View Comments (0) ...
Navigation