From Localhost to Live: Deploy Your Backend to AWS EC2

Ronak PaulRonak Paul
7 min read

It’s always easy to deploy your frontend in a click with the help of various platforms like vercel, netlify, Github Pages etc. But it is somewhat tricky to deploy your backend to the cloud so that everyone can hit it.

Although platforms like vercel, renderer also supports deploying your backend in a click but it is always recommanded to host your backend in your own server using a cloud platform like AWS, GCP, Azure etc because those platforms ( vercel and renderer ) adds latency and stops working when not hitted for weeks.

While you are developing a Full Stack Project as a side project or for a hackathon, you may encountered the problem of deploying your backend. So I am gonna make this easy for you by writing this blog.

Let’s get started. 💪

I will not gonna explain how to setup a AWS account. It should be straight forward if you are a dev. 🤷‍♂️

Launch EC2 instance

To launch a EC2 instance, search EC2 in the search bar and select it then click on the Launch instance button.

Now, you will get the below screen.

Give a name to your server and select the Ubuntu OS image.

Keep the Instance type as t2.micro for the free tier (It gives 750 hours per month of t2.micro instance usage) and then create a key pair if you don’t have one or use the existing one.

‼️ You should have the pem file in your computer to SSH to this server so keep it safe.

Now in the Network settings you can allow HTTPS and HTTP traffic from the internet by selecting the checkboxes.

Now you can click on the Launch instance button in the right side.

You can check all your running instances over EC2 > Instances

SSH EC2 Server

SSH connection to your newly created EC2 server is simple. Just click on the instance ID from the row and copy the Public DNS. Then do the following:

  • Open your terminal

  • Locate your private key file in the terminal using the cd command

  • Change the file permission of the pem file using the below command to make sure that the file is not publicly viewable

      chmod 400 "your-pem-file-name.pem"
    
  • Connect to your server’s public DNS using SSH

      ssh -i "your-pem-file-name.pem" ubuntu@your_public_dns
    

After running the above command, you will see this screen and then you are good to run commands remotely in your AWS EC2 server.

Writing a simple backend

Let’s write a simple backend using Express.js. The backend will simply increment a counter and store the value in a variable and you can also retrieve the counter value using another route. You can deploy any of your backend code using this method.

  • Create a folder named “backend-test“ or anything of your choice and cd into it.

  • Install the required packages using npm

      npm install express
    
  • Create a index.js file and paste the below code there.

      const express = require("express")
    
      const app = express();
    
      const PORT = 8000;
    
      let counter = 0;
    
      app.get("/incre", (req, res) => {
          counter++;
    
          res.status(200).json({message:"Incremented the counter successfully"})
      })
    
      app.get("/status", (req,res) => {
          res.status(200).json({message:"status fetched successfully", counter})
      })
    
      app.listen(PORT, () => {
          console.log(`Server is running at ${PORT}`)
      })
    
  • Now run the server using the below command. This will run the server in your local environment. You can test the endpoints in postman or directly from the browser since these are GET endpoints.

      node index.js
    

Now you have to push your local code to GitHub so that you can pull it in your EC2 server and spin it up there.

Setup Backend Code in EC2

Until now you pushed your local backed code to GitHub. Now you have to pull it into your EC2 server. So do the following to start the backend in your EC2 server.

  • SSH into the server using the above instructions

  • Install Node in the EC2 server using NVM ( Node Version Manager )

      curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash
    

    Now exit from the ubuntu shell and again SSH. Then run the below command

      nvm install --lts
    

    It will download the latest LTS version of node into the server. You can check the node version using the node —-version command.

  • Now pull your code from the GitHub using the below command and cd into the folder.

      git pull "<Github Repo URL>"
    
  • Now install the node modules using npm install command and start the index file using the node index.js command

  • Now you can hit the public DNS with the given port of your backend application, in this case it is 8000. But you will see that it can’t hit the URL, it will keep loading

  • In this case you need to update the inbound roules of the security group.

  • Now again try hitting the public DNS with the port and correct route. You will see the response like below

    But, you can see that it is showing Not Secure in the search bar. We will fix it by adding a certificate to it.

Setup NGINX

Before setting up nginx, you need to know why we are using nginx.

Nginx (pronounced "engine-X") is an open-source web server and reverse proxy, widely recognized for its high performance, scalability, and low resource usage. It also functions as a load balancer, HTTP cache, and mail proxy.

Here we will use nginx as a reverse proxy. A reverse proxy server acts as an intermediary between clients and one or more backend servers. It sits in front of the servers, receiving client requests and forwarding them to the appropriate server, while also returning responses from the server back to the client.

Now let’s install and setup nginx into the EC2 server using the below steps:

  • Installing nginx

      sudo apt update
      sudo apt install nginx
    
  • After installing nginx, try hitting the same public DNS and you will see the following response if it is successfully installed.

  • Now we will create the reverse proxy. To do that run the below commands in the root of the server

      sudo rm sudo vi /etc/nginx/nginx.conf
      sudo vi /etc/nginx/nginx.conf
    

    And paste the below code into it.
    Please replace the server name with your own purchased domain name.

      events {
          # Event directives...
      }
    
      http {
          server {
          listen 80;
          server_name bt.ronakpaul.com;
    
          location / {
              proxy_pass http://localhost:8000;
              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;
          }
          }
      }
    

Domain and Certificate

Now you need to add domain name record to point your domain name to the server ip address. To do so, go to the platform from where you had purchased the domain, for me it is hostinger.

Add a A name record to the platform like below. You can give any subdomain name and it should point to the AWS EC2 public ip address.

Now you can see that we can hit the server using our own domain

Now we have to add the certificate, so that it can be accessed using https. To add a certificate, do the following:

  • Run this command in the server to install Certbot.

      sudo snap install --classic certbot
    
  • Execute the following command in the server to ensure that the certbot command can be run.

      sudo ln -s /snap/bin/certbot /usr/bin/certbot
    
  • Now, run the below command to get a certificate and have Certbot edit your nginx configuration automatically to serve it, turning on HTTPS access in a single step.

      sudo certbot --nginx
    
  • It’s done. Now you just need to run the index.js file using pm2 ( Process Manager 2 ) so that the process does not stop when you exit from the terminal or shutdown the pc. To do so, install pm2 by the below command

      npm install pm2 -g
    

    Start the index.js file using pm2

      pm2 start index.js
    

Now you can finally see that your backend is fully deployed and accessable over https on your own domain.

So you now can connect your backend with frontend by hitting it with fetch or axios.

Happy coding guys ☕️

4
Subscribe to my newsletter

Read articles from Ronak Paul directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ronak Paul
Ronak Paul

I am a full stack developer and student from India. Building and contributing to community.