Deploying Next.js on Ubuntu with SSL with Nginx, letsencrypt& Pm2
I know we all have gone through the trouble of deploying our application on a linux server where we have to set everything right. Their are many ways i would prefer than direct deployment but I know this guide will be handy for many developers out their.
Overview Steps
- Setup Ubuntu 20.x.x and SSH
- Install Node.js via NVM & pm2 globally. execute these commands:
sudo apt install curl
curl https://raw.githubusercontent.com/creationix/nvm/master/install.sh | bash
source ~/.bashrc
nvm install node
node -v
npm install pm2 -g #this will install pm2 package
- Install Nginx and Letsencrypt.
sudo apt-get update
sudo apt-get install nginx letsencrypt certbot python3-certbot-nginx
sudo ufw allow 'Nginx Full'
- Now clone your project & install dependencies
git clone <my-nextjs-project.git>
cd <my-nextjs-project>
npm install
npm run build
- Now that we have everything ready, its time to deploy our project. The following command will run your project with pm2 clustering mode enabled.
pm2 start npm --name "<my-nextjs-project>" -i 0 -- run start
Now if you open up http://<your-ip-address>:3000, You will be able to see your project.
We have our project running on port 3000, you can also change it by passing PORT=80 or something but for Next.js convienance, we will keep it as PORT 3000.
Point your domain to the IP Address
Point your domain to the IP address of your server, add following A Records
A Record — — — — — — @ — — — <server-ip>
A Record. — — — — — -wwww — — -<server-ip>
Setting up Nginx with SSL Certificate
Time to configure Nginx to use the PORT 3000 as default for your website.
First thing is we need SSL Certificate alongside key & we will put them at /ssl/<my-website>.cert.pem and /ssl/<my-website>.key.pem
We will issue that with Letsnecrypt by following these commands:
## Setup Letsencrypt
sudo certbot --nginx -d your-website.com -d www.your-website.com
This will do the magic!