Express + Nginx

This show which commands to use to setup Express apps with Nginx

Prerequisites

A host is needed to run an web server. There are a variety of good hosting options to use. My recommendation is Digital Ocean. They have a user friendly interface.

A registered domain is required. Google Domains is a good registrar.

A basic understanding of Secure Shell and SFTP is a must. Use the following links if you need to learn:

Setup

I will be using Ubuntu in this example. Run this command to update all applications:

sudo apt update && sudo apt upgrade -y

Here we will create a website directory and enter it.

mkdir website && cd website

Node.js is required to run the express application.

curl -sL https://deb.nodesource.com/setup_13.x | sudo -E bash -
sudo apt-get install -y nodejs

PM2 is my favorite process manager for node.js applications. It will restart anytime the app crashes and can reload when changes in the code are detected.

npm i -g pm2

We will be running an express application so we must install the module.

npm i express

Opening ports to allow web traffic

sudo ufw enable && sudo ufw status && sudo ufw allow ssh && sudo ufw allow http && sudo ufw allow https

Install Nginx web server.

sudo apt install nginx

Server

Edit the server configuration file located in: /etc/nginx/sites-available/default

default
server {
listen 80;
server_name example.com;
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;
}
}

Check to see if file syntax is good: sudo -t nginx

Lastly restart Nginx to save changes: sudo service nginx restart

Code

Open app.js (you can use WinSCP to do this) and use this sample code:

app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => res.send('Hello World!'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));

Finally run app with PM2: pm2 start app.js

Extra