Minimal Express Server with Nginx and PM2

Share:

Source Code

Tools we’ll use

Digital Ocean: A high quality, low cost VPS provider.

Nginx: Extremely performant reverse proxy used by millions of websites.

Express: The default server side middleware framework for NodeJS.

PM2: Great process manager for NodeJS applications.

Create a droplet

Create a NodeJS droplet from Digital Ocean’s control panel, a simple $5/month droplet is enough for our example.

Once you received an email with your credentials, ssh into the server:

ssh root@MY_IP_ADDRESS

Installing Nginx

Let’s install Nginx with the following commands:

sudo apt-get update
sudo apt-get install nginx

verify Nginx is running by going to your server’s ip in the browser, if you did it correctly, you should see the “Welcome to Nginx” message.

There are two directories you need to know about in order to do configuration related tasks. The first directory is /etc/nginx/sites-available, this is where you store the configuration file for your web server, there should be a file called default in there. The other directory is the public directory where you serve your website: /usr/share/nginx/ . We’ll revisit those later.

Installing Express and Express Generator

Navigate to /usr/share/nginx/ directory and install express generator by

npm install express-generator -g
express myapp
cd myapp
npm install

You should now have a simple scaffolding for a minimal express project in the myapp directory. Test it out by going to the directory and run

npm start

then head over to your server: http://your_server_ip:3000

you should see a “Welcome to Express” message.

Set up Nginx for Express app

We don’t want our users to type in :3000 every time they visit our website, so we need to let Nginx know to proxy the default port 80 requests to our Express app.

Let’s go to /etc/nginx/sites-available/ folder and edit the default file

right before the server block, add the following:

upstream node_app {
   server 127.0.0.1:3000;
}
bad

and within the server block, add this line to location / block

proxy_pass http://node_app;

Your final Nginx config file should look like this

If you go to your server without the :3000, it should show the Welcome to Express message!

Set up PM2

You can install PM2 with one simple command

npm install pm2 -g

Go in to myapp directory and create a config file named pm2config.json

then run

pm2 start pm2config.json

and you the app should now be managed by pm2! Head over to the browser and your website should still load.

I hope you find this quick guide useful.

Comments Or Questions? Discuss In Our Discord

If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!

More from PentaCode