Skip to content

Instantly share code, notes, and snippets.

@JDeepD
Last active October 28, 2024 13:38
Show Gist options
  • Save JDeepD/104cf0019fee62ff27ba54e39f8072df to your computer and use it in GitHub Desktop.
Save JDeepD/104cf0019fee62ff27ba54e39f8072df to your computer and use it in GitHub Desktop.
NodeJS Backend Deployment on AWS
  1. Create an AWS EC2 Instance with Ubuntu AMI.
  2. SSH into the EC2 instance.
  3. Install fnm : curl -fsSL https://fnm.vercel.app/install | bash
  4. Select a Node version to install. For example : fnm use 20 (Will install Node v20)
  5. Install pnpm: npm i -g pnpm and setup : pnpm setup
  6. Clone your backend into EC2.
  7. Install pm2 : pnpm i -g pm2.
  8. Install project depedencies: pnpm install --frozen-lockfile
  9. Put Environment Variables in .env.
  10. If you have a domain for the API, go to manage DNS records and create an A record with value as the EC2 Public IP.
  11. Install Nginx to use as a Reverse Proxy: sudo apt install nginx. Ensure it is running : sudo systemctl status nginx.
  12. Now, cd into etc/nginx/sites-available. Create a nginx configuration file which routes incoming HTTP traffic for server {YOUR_API_DOMAIN} to our express app running at localhost:{PORT}. Example Nginx Config:
server {
  listen 80;
  server_name {YOUR_API_DOMAIN};
  location / {
    proxy_pass http://localhost:{PORT};
  }
}
  1. You can name the config file as anything but it is good practice to name it same as your domain. For ex, the config file could be named api.guidancegrid.gdscnits.in. Create a symlink for this file in /etc/nginx/sites-enabled. (Only configs in sites-enabled will be used by nginx).
sudo ln -s /etc/nginx/sites-available/{YOUR_CONFIG_FILE_NAME} /etc/nginx/sites-enabled/
  1. Test if the nginx config is valid sudo nginx -t. If there are no errors, restart nginx : sudo systemctl restart nginx.
  2. Check if the endpoint works without specifying a PORT now: http://{YOUR_API_DOMAIN}/api/v1.
  3. To set up SSL certificates, we will use letsencrypt. Install certbot and python3-certbot-nginx.
sudo apt install certbot
sudo apt install python3-certbot-nginx
  1. Request an SSL certificate for your registered domain. The certbot-nginx plugin will automatically configure the certificate for your domain. sudo certbot --nginx -d {YOUR_API_DOMAIN} It will ask for email. Enter it and accept all terms and conditions.

  2. If there were no errors, you should see a message that tells you that SSL certificate has been installed successfully on your domain.

  3. Go to https://{YOUR_API_DOMAIN}/api/v1 to check if the endpoint is working.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment