Step by step instructions on how to setup, secure, and host a node application on Ubuntu 16.04 (using Nginx and PM2).
Basic Server Setup
Here’s all the basic steps you should take on a fresh Ubuntu install.
#precedence ::ffff:0:0/96 100 and save.
Updating package lists and upgrading installed packages
Setting a hostname
Setting the time
Fully qualified domain name setup
Set up a fully qualified domain name by editing
/etc/hosts to look like the second snippet below.
Creating a new sudo ubuntu user and logging into it
Switching to public key authentication
Create a new folder
.ssh and file
Open your SSH public key from your local computer and copy it’s contents to your clipboard. The file is usually located at
~/.ssh/id_rsa.pub. If you don’t have a SSH key pair you can create one by opening a new terminal tab and type
Now that you have your ssh public key copied let’s paste it in our newly created
control + x and
control + y to save an exit the file.
Change the folder and file permissions.
Testing public key authentication
Now that we have our public key in place, we should be able to login without using our Ubuntu user password. Logout and back into your account.
If it didn’t prompt you for a password you’re good to go.
Disabling root login, and password login
Disable root login by changing
PermitRootLogin yes to
Disable password authentication by un-commenting
#PasswordAuthentication no. Restart the service with the following command:
We can install Nginx super easy using
UFW Firewall Setup
Set up a simple firewall using UFW. It’s most likely already installed, but just incase run the
sudo apt-get install ufw.
Next set up some basic rules to allow all outgoing connections and block all incoming connections except on though ssh (22) and the required nginx ports for http and https (80 and 443).
You can verify everything is set up correctly by running the following command:
Installing Node JS
NodeJS can be installed via package manager by running install commands found on the NodeJS installation page.
Verify Node JS is installed by running version check.
You will also want to install the optional build-essential package.
PM2 is a npm package that manages your node processes and will restart them on crash.
Hosting a node app
Now that we have all the basics covered we are finally ready to host our first Node application.
Nginx Virtual Host Block
Inside this file we place our nginx config. This config basically just makes nginx a middleman between incoming traffic an our node app.
Next we have to symbolic link this to the sites-enabled directory, and restart Nginx.
Installing our app
Upload your app somewhere on the sever. I stick with the normal
/var/www/<website.tld> placement. Upload your files there then install and start the process.
Lastly we’ll tell PM2 to startup automatically on reboot.
This command will output a command for you to run, run it. Mine looks like this.