Setting up Node.JS for production
- Install Node.JS
- Install and configure PM2
- Setting up Let's Encrypt
First, make sure you have Node.js installed on your system. If you don't have it already, you can install it from the official website or by following the steps below.
NVM via curl and install it.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
NVM as a command to your terminal.
export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
Restart your terminal
Install Node.js's latest
nvm install --lts
Next, install PM2 using the following command:
npm install -g pm2
Now, you can start a new Node.js application using PM2 with the following command:
pm2 start app.js
Replace "app.js" with the name of your Node.js script file. This will start your application and keep it running in the background.
To view the status of your application, use the following command:
This will show you the status of all the applications managed by PM2, including their process ID, name, and current status.
If you need to stop an application, you can use the following command:
pm2 stop app
To restart an application, use the following command:
pm2 restart app
By using PM2 to manage your Node.js applications, you can ensure that they are always running and automatically restart them in the event of any failures. This can save you a lot of time and effort in the long run.
Using HTTPS with Certbot
Let's Encrypt is a free, automated, and open certificate authority that provides SSL/TLS certificates to secure websites and protect them from cyber threats.
Install the Certbot client, which is a command-line tool that allows you to request and renew SSL/TLS certificates from Let's Encrypt. You can install Certbot from the official website or with the command below.
sudo apt install certbot python3-certbot-nginx
Before we get started run we will need to delete the old
Nginx HTTP and allow the full Nginx profile to pass through your firewall.
sudo ufw allow 'Nginx Full' sudo ufw delete allow 'Nginx HTTP'
Once Certbot is installed, run the following command to obtain a certificate for your Nginx server:
sudo certbot --nginx -d example.com -d www.example.com
-d flag is used for assigning a domain/sub-domains to your certificate. Replace
example.com with your domain.
That's it! Your Nginx server is now secured with a Let's Encrypt SSL/TLS certificate. Let's Encrypt certificates are valid for 90 days, so it's important to set up a renewal process to ensure that your certificate doesn't expire. You can use the Certbot client to automatically renew your certificate by running the following command:
sudo systemctl status certbot.timer