Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
117 lines (78 sloc) 2.82 KB
description
This show which commands to use to setup Express apps with Nginx

Express + Nginx - Ubuntu

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.

{% embed url="https://andre.gg/digitalocean" caption="You can use my referral link to get $50 in credit over 30 days" %}

{% hint style="info" %} A registered domain is required. Google Domains is a good registrar. {% endhint %}

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

{% embed url="https://www.howtogeek.com/311287/how-to-connect-to-an-ssh-server-from-windows-macos-or-linux/" %}

{% embed url="https://www.youtube.com/watch?v=58KmUBaEW34" %}

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

{% embed url="https://pm2.keymetrics.io/" %}

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

{% code title="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;
    }
}

{% endcode %}

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:

{% code title="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}!`));

{% endcode %}

Finally run app with PM2: pm2 start app.js

Extra

{% embed url="https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04" %}

You can’t perform that action at this time.