After deploying the application to EC2, we will initialize CloudFront to improve the website’s performance
Go to the CloudFront interface and select Create distribution
In Create distribution, select the following options:
It will take about 5-10 minutes to create. Once successfully created, you will see Last modified
In the newly created distribution, go to the Behaviors tab
Click Create Behavior
In Create behavior, fill in the following details:
/api/*
Click Create behavior
Connect to EC2 using EC2 Instance Connect
Run the following command to open the .env file for editing
cd e-commerce-furniture
nano .env
In .env, update NEXT_PUBLIC_API_URL to the Distribution domain name of CloudFront, then press Ctrl + X -> Y -> Enter to save
After updating the .env file, run the following command to rebuild the project
npm run build
Once the build is complete, restart pm2
pm2 restart all
Reasons for using Nginx in this workshop:
Reverse Proxy:
Initially, the application runs on EC2 at port 3000. Nginx helps redirect (proxy_pass) requests from ports 80 or 443 to 3000, allowing access via the domain name or CloudFront without specifying a port
For example, after setup, you can access: http://your-ip-ec2 (without :3000). Nginx will automatically forward requests to localhost:3000 (where your application runs)
Install Nginx
sudo apt update
sudo apt install nginx -y
Configure Nginx to redirect CloudFront
Edit the Nginx config file:
sudo nano /etc/nginx/sites-available/default
Add the following:
server {
listen 80;
server_name _;
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;
}
}
Save the file (Ctrl + X → Y → Enter)
Check for configuration errors
sudo nginx -t
If no errors are found, restart Nginx
sudo systemctl restart nginx
We can compare the performance between EC2 (left) and CloudFront (right) -> CloudFront has optimized the performance over EC2
![]() | ![]() |
---|