Tutorial on how to setup a node.js application behind nginx
In this brief tutorial we will setup how to configure a small production application that will use nginx as a reverse proxy for serving the node.js application. For managing node.js application we will use PM2.
In the next steps we are going to install node.js in the /opt directory. Check the node version on the url, if this blog post becames old you can change the version on the url.
Add the user for execute the node.js application
Deamonize node.js application
We need to deamonize our node.js process to allow it to be restarted automatically if the application crashes or is killed. For this purpose we are going to use PM2, which is a node.js process manager for node.js applications.
The startup subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots
if you are using ubuntu try to use “ubuntu” instead systemd.
In my case I was trying to configure a keystone.js project, so I started it with this command (start it with the nodejs app unix user):
you should see your process in the list of PM2.
Check that the node.js process is working with (change the port if necessary):
if for some reason your app is not working check the subcommand logs
We will use nginx as a reverse proxy. This tutorial required nginx already installed, so we are going directly to site configuration. Also this tutorial assumes that your are using the “sites-available” and “sites-enables” to configure more than one domain.
Add a new file to /etc/nginx/sites-available with the following: