Deploy React Frontend and Django Backend on AWS EC2 Instance

Deploy React Frontend and Django Backend on AWS EC2 Instance

Table of Contents

  1. AWS EC2 Instance Setup

  2. Attaching Elastic IP

  3. Adding Domain on Cloudflare

  4. Necessary Packages Installation on AWS EC2

  5. Frontend Deployment

  6. Backend Django Deployment

  7. Nginx Setup

  8. Additional Notes


Part 1: AWS EC2 Instance Setup

  1. Launch an EC2 Instance:

    • Choose the required instance type, such as a t2.micro for small projects or something larger depending on your project’s needs.

    • Allow inbound traffic for SSH (port 22), HTTP (port 80), and HTTPS (port 443) in the security group.

  2. Connect to Your EC2 Instance:

    • Use SSH to securely connect to your instance with the ssh command using your .pem key.

Why:
The EC2 instance provides a cloud-based server where you’ll host both the React frontend and Django backend. Setting up the correct security group allows necessary traffic for managing and accessing the server.


Part 2: Attaching Elastic IP

  1. Allocate Elastic IP:

    • In your AWS EC2 dashboard, navigate to "Elastic IPs" and allocate a new Elastic IP.
  2. Associate the Elastic IP with Your EC2 Instance:

    • Associate the Elastic IP with your running EC2 instance.

Why:
Elastic IP ensures that your EC2 instance retains a static IP address, even if it is stopped or restarted. This makes it easier to configure DNS and provides users a consistent way to access your site.


Part 3: Adding Domain on Cloudflare

  1. Login to Cloudflare:

    • If you don’t have a Cloudflare account, sign up and log in.
  2. Add Domain:

    • Add your domain to Cloudflare and follow the steps to update the name servers on your domain registrar.
  3. Update DNS Settings:

    • Go to the DNS section and point your domain and subdomains (e.g., api.yourdomain.com for the backend) to your EC2 instance’s Elastic IP.

Why:
Cloudflare helps manage your domain’s DNS, boosts site performance using caching and a CDN, and adds security features. It allows users to access your website through your domain and provides free SSL certificates for HTTPS.


Part 4: Necessary Packages Installation on AWS EC2

  1. Update the Package Manager:

    • Run sudo apt-get update to ensure the package manager has the latest info.
  2. Install Node.js (Version 20) and npm:

    • Install Node.js using the command provided:

        bashCopy codecurl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
        sudo apt install -y nodejs
        sudo apt install npm -y
      
  3. Install Nginx:

    • Run sudo apt install nginx -y to install Nginx.

Why:
Node.js and npm are required to build and run the React application, while Nginx acts as the web server and reverse proxy for managing traffic between the frontend and backend. Keeping packages updated ensures system stability.


Part 5: Frontend Deployment

  1. Clone the React App from GitHub:

    • Clone your React app onto the EC2 instance:

        bashCopy codegit clone <YOUR-GIT-Repo>
      
  2. Install Required Dependencies:

    • Navigate to the project folder and install dependencies using npm:

        bashCopy codecd <project-folder>
        npm install
      
  3. Create Production Build:

    • Build your React app for production:

        bashCopy codenpm run build
      
  4. Set Up Directory and Copy Build:

    • Create a directory where Nginx will serve the build:

        bashCopy codesudo mkdir -p /var/www/vhosts/frontend/
        sudo cp -R build/ /var/www/vhosts/frontend/
      

Why:
Cloning the React repository onto the EC2 instance and installing dependencies prepares your frontend code for deployment. The npm run build command creates an optimized production version of your React app, and copying the build to a directory allows Nginx to serve it.


Part 6: Backend Django Deployment

  1. Install Python and Virtualenv:

    • Install Python, pip, and the virtual environment tool:

        bashCopy codesudo apt update
        sudo apt install python3-pip python3-dev python3-virtualenv
      
  2. Clone the Django Project:

    • Clone the Django project and navigate to the project directory:

        bashCopy codegit clone <YOUR-DJANGO-REPO>
        cd <YOUR-DJANGO-PROJECT>
      
  3. Set Up Virtual Environment:

    • Create and activate a virtual environment:

        bashCopy codevirtualenv venv
        source venv/bin/activate
      
  4. Install Dependencies:

    • Install the required Python packages:

        bashCopy codepip install -r requirements.txt
      
  5. Configure Django Project:

    • Update the ALLOWED_HOSTS in your settings.py and collect static files:

        bashCopy codepython manage.py makemigrations
        python manage.py migrate
        python manage.py collectstatic
      
  6. Install and Configure Gunicorn:

    • Install Gunicorn:

        bashCopy codepip install django gunicorn
      
    • Configure Gunicorn to start as a systemd service by creating a service file:

        bashCopy codesudo vim /etc/systemd/system/gunicorn.service
      

Why:
Python and virtualenv are required to set up the Django backend. Gunicorn is the recommended server for running Django applications in production, allowing for better performance and serving the app to the Nginx web server. Running migrations and collecting static files prepares your Django app for production.


Part 7: Nginx Setup

  1. Remove Default Configuration:

    • Remove the default Nginx configuration:

        bashCopy codesudo rm /etc/nginx/sites-enabled/default
      
  2. Set Up Nginx Configuration for Frontend and Backend:

    • Create an Nginx configuration file and paste the following configuration:

        bashCopy codesudo vim /etc/nginx/sites-available/nginx
      
    • Frontend Nginx Config:

        nginxCopy codeserver {
            listen 80;
            server_name YOUR_DOMAIN.com;
      
            location / {
                autoindex on;
                root /var/www/vhosts/frontend/build;
                try_files $uri $uri/ /index.html;
            }
        }
      
    • Backend Nginx Config:

        nginxCopy codeserver {
            listen 80;
            server_name api.YOUR_DOMAIN.com;
      
            location / {
                include proxy_params;
                proxy_pass http://unix:/run/gunicorn.sock;
            }
        }
      
  3. Enable and Restart Nginx:

    • Enable the Nginx configuration and restart the server:

        bashCopy codesudo ln -s /etc/nginx/sites-available/nginx /etc/nginx/sites-enabled/
        sudo systemctl restart nginx
      

Why:
Nginx acts as a reverse proxy, routing traffic to both the React frontend (static files) and the Django backend via Gunicorn. Setting up this configuration ensures that requests are handled correctly and the right service is returned based on the URL (frontend or backend).


Part 8: Additional Notes

  1. Check the Status of Nginx and Gunicorn:

    • Run the following commands to ensure Nginx and Gunicorn are running:

        bashCopy codesudo systemctl status nginx
        sudo systemctl status gunicorn
      
  2. Review Logs for Errors:

    • If any issues arise, check the logs for more details:

        bashCopy codesudo tail -f /var/log/nginx/error.log
      

Why:
Checking the status of Nginx and Gunicorn helps ensure your services are running as expected. Reviewing logs allows you to troubleshoot any issues that may arise during the deployment process.


This detailed explanation now integrates both the deployment steps and the reasoning behind each action, ensuring a smooth setup for deploying a React frontend and Django backend on AWS EC2.

More resources
1. Deploy a React/Node app on EC2 with Redis,PostgrSQL and SSL encrypted https
2. Deployment of website