Skip to content

Instantly share code, notes, and snippets.

@avoidik
Created April 26, 2022 10:44
Show Gist options
  • Save avoidik/bc5d999294039fda5602a814059697e8 to your computer and use it in GitHub Desktop.
Save avoidik/bc5d999294039fda5602a814059697e8 to your computer and use it in GitHub Desktop.
Basic Nginx reverse proxy for NodeJS application

How to configure

Steps

Install dependencies

sudo apt-get update -y -q
sudo apt-get install -y -q nginx certbot python3-certbot-nginx
sudo apt-get install -y -q nodejs npm

Prepare work directory

mkdir web
cd web
npm init -y
nano server.js

Use this simple nodejs web app

const http = require('http');

const hostname = '127.0.0.1';
const port = 8080;

const server = http.createServer((req, res) => {
	res.statusCode = 200;
  	res.setHeader('Content-Type', 'text/plain');
  	res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  	console.log(`Server running at http://${hostname}:${port}/`);
});

Unlink default Nginx configuration

sudo unlink /etc/nginx/sites-enabled/default

Create new Nginx configuration

sudo nano /etc/nginx/sites-available/my-server
server {
    listen 80;
    server_name _;
    proxy_buffering off;
    proxy_request_buffering off;
    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_pass http://127.0.0.1:8080;
    }
}

Test and enable new Nginx configuration

sudo ln -s /etc/nginx/sites-available/my-server /etc/nginx/sites-enabled/my-server
sudo nginx -t
sudo systemctl reload nginx

Test run

nodejs server.js

Make Nodejs application to run as a service

sudo nano /etc/systemd/system/my-server.service
[Unit]
Description=my-server
Documentation=run my-server as system daemon
After=network.target

[Service]
Type=simple
User=ubuntu
ExecStart=/usr/bin/node /home/ubuntu/web/server.js
WorkingDirectory=/home/ubuntu/web
Restart=on-failure

[Install]
WantedBy=multi-user.target

Enable systemd service

sudo systemctl daemon-reload
sudo systemctl enable my-server.service
sudo systemctl start my-server.service
sudo systemctl status my-server.service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment