Sunday, May 26, 2024

Deploying Your Node.js App on EC2 (Amazon Web Services) with PM2 and NGINX

In this blog, I am going to discuss about how to deploy your Node JS and Express application in AWS EC2 instance. Along with deploying the application I am also setting up the NGINX server and PM2 (Process Manager) library. I have shown all these steps clearly in this Youtube video. Please go through the video to get the complete and clear idea.

NOTEThe URL of this video: https://youtu.be/z0GkpPYwl8o


Steps:

1) Create your free trial AWS login
2) Commit your code to GitHub
3) Create EC2 instance:        
  • Create an EC2 instance. Basically t2-micro ubuntu
  • Connect to your EC2 instance
  • Trigger sudo apt update to install any update if available
4) Install node js version 18:
  • sudo apt install nodejs
  • node -v
  • npm -v
5) Verify if GIT and clone your project :
  • git --version
  • git clone YOUR_PROJECT_REPOSITORY_URL
6) Project configuration:
  • Go inside your project folder: cd youtubeCode
  • Trigger command "npm install" to create the node_module folder
  • Verify node_module folder by command "ls"
7) Install Process Manager(PM2) library at global level
  • sudo npm install -g pm2
  • Then go to your project folder
  • pm2 start app.js
  • pm2 logs
  • pm2 reload all
8) Now you can visit your api in browser: http://IP:Port/routeName
9) Install nginx and configure:
  • sudo apt install nginx
  • sudo vim etc/nginx/sites-available/default andthen add below configs in this default file
server_name 54.206.158.160;
location / {
proxy_pass http://localhost:3001;
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;
}
  • Press ctrl+c and type :wq! to write and quit
  • Check NGINX config by command "sudo nginx -t". If it is returning success that means your NGINX server is configured properly and you can run your application on your NGINX server.
10) Start your NGINX server: sudo systemctl stop nginx
11) If any changes are being done in NGINX configuration, then you have to restart your NGINX server by command like sudo systemctl start nginx
12) If all steps are being followed properly, then till here, your application will be deployed and running successfully on NGINX server using PM2 library on AWS EC2 instance and now you can access your API just by using your EC2 instance's public IP address. No need to provide the port number. By default NGINX is running on PORT 80 and security group of EC2 instance in AWS is already having inbound rule to allow the traffic from 80 port.

No comments:

Post a Comment

Please provide your precious comments and suggestion