Deploy NodeJs Application On Ubuntu and Nginx
Chandra Prakash Pal
Posted on June 21, 2024
When using the Nginx web server, server blocks (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain on a single server.
In this guide, we’ll discuss how to configure server blocks in Nginx on an Ubuntu.
Login on remote machine by ssh
First login on remote machine by ssh as follows
ssh user@remote_ip
After login on remote install nodejs on machine, if already installed then ignore it.
You can check installation guide from here
Clone your project from Github
There are a few ways to get your files on to the server, I would suggest using Git
git clone yourproject.git
Install dependencies and test app
`cd yourproject
npm install
npm start (or whatever your start command)
stop app
ctrl+C`
Setup ufw firewall
sudo ufw enable
sudo ufw status
sudo ufw allow ssh (Port 22)
sudo ufw allow http (Port 80)
sudo ufw allow https (Port 443)
Install NGINX and configure
sudo apt install nginx
sudo nano /etc/nginx/sites-available/default
Add the following to the location part of the server block
`server {
server_name your_domain www.your_domain;
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 NGINX config
sudo nginx -t
Restart NGINX
sudo service nginx restart`
Make the symbolik linking by running following
sudo ln -s /etc/nginx/sites-available/{your_domain or folder name in sites_availabe}/etc/nginx/sites-enabled
Secure Nginx with Let's Encrypt
Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps.
Installing Certbot
sudo apt install certbot python3-certbot-nginx
Confirming Nginx’s Configuration
To check, open the configuration file for your domain using nano or your favorite text editor:
sudo nano /etc/nginx/sites-available/example.com
Find the existing server_name line. It should look like this:
/etc/nginx/sites-available/example.com
...
server_name example.com www.example.com;
...
If it does, exit your editor and move on to the next step.
verify the syntax of your configuration file
sudo nginx -t
Once your configuration file’s syntax is correct, reload Nginx to load the new configuration:
sudo systemctl reload nginx
Obtaining an SSL Certificate
sudo certbot --nginx -d example.com -d www.example.com
Credits goes to following references
NodeJS App Deployment On Ubuntu Server
How To Set Up a Node.js Application for Production on Ubuntu 20.04
Posted on June 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.