Deploying a React Application on AWS EC2 with CI/CD using AWS CodeDeploy

In the world of web development, deploying an application is a crucial step in making it accessible to users worldwide. In this blog, we'll walk through the process of configuring an AWS EC2 instance and deploying a React application on it. We'll also set up Continuous Integration and Continuous Deployment (CI/CD) using AWS CodeDeploy, streamlining the deployment process.

Prerequisites

Before we dive into the steps, here are a few prerequisites:

  1. AWS Account: You need an AWS account to create and manage EC2 instances, IAM roles, and other AWS services.


  2. React Application: Ensure you have a React application ready to deploy. You can build one or use an existing project.


  3. AWS CLI: Install the AWS Command Line Interface (CLI) on your local machine to interact with AWS services.

Step 1: Create an EC2 Instance

  1. Log into AWS Console: Sign in to your AWS account and access the AWS Management Console.


  2. Launch EC2 Instance: Navigate to the EC2 service. Click "Launch Instance" to create a new EC2 instance.


  3. Choose an Amazon Machine Image (AMI): Select an AMI that suits your needs. An Amazon Linux or Ubuntu Server AMI is often a good choice.


  4. Instance Type: Choose the instance type based on your application's resource requirements. For a React app, a t2.micro instance is usually sufficient.


  5. Configure Instance Details: Set up the instance details, including the number of instances, network settings, and IAM role.


  6. Add Storage: Configure the storage settings for your instance. The default settings are typically sufficient.


  7. Add Tags: Optionally, add tags to your instance for better organization.


  8. Configure Security Group: Set up the security group to control inbound and outbound traffic. Make sure to allow SSH access for administration.


  9. Review and Launch: Review your instance configuration and launch it. You'll need to create or use an existing key pair for SSH access.


  10. Launch Status: Once your instance is running, note its Public IP address.











Step 2: Install node and git

    1. Install NVM (Node Version Manager):


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

       

       This command downloads and runs the NVM installation script from its GitHub repository. It installs NVM, a tool for managing multiple Node.js versions on your system.

    1. Activate NVM:


    2. . ~/.nvm/nvm.sh

    3. This command activates NVM, making it available in your current shell session.


    4. Install the Latest LTS (Long Term Support) Node.js Version:

    5. nvm install --lts

       

    6. This command uses NVM to install the latest LTS version of Node.js, which is recommended for most production applications.


    7. Check Node.js Version:


    8. node -e "console.log('Running Node.js ' + process.version)"

    9. This command prints the currently active Node.js version to the console.




    1. Install Git:


    2. sudo yum install git

    3. This command installs Git on your system, which is a version control system used to manage source code.


    4. Check Git Version:


    5. git version

    6. This command verifies that Git is installed and displays its version.




    1. Clone a Git Repository:


    2. git clone https://github.com/ipreencekmr/my-dynamic-app.git

    3. This command clones (downloads) a Git repository from the specified URL to your local machine. Replace the URL with the repository you want to clone.


    4. Navigate to the Cloned Repository:


    5. cd my-dynamic-app/

    6. Use cd to change your current directory to the cloned repository.


    7. Install Project Dependencies (Assuming it's a Node.js Project):


    8. npm install

    9. This command installs the project's dependencies using npm, the Node.js package manager.



    1. Install PM2 Globally:


    2. npm install pm2 -g

    3. This command globally installs PM2, a process manager for Node.js applications.



    1. List PM2 Processes:


    2. pm2 list

    3. This command lists all the processes managed by PM2. It should be empty if you haven't started any processes yet.


    4. Start Your Node.js Application with PM2:


    5. pm2 start --name my-dynamic-app npm -- start -p 3000

    6. This command starts your Node.js application with PM2, giving it the name "my-dynamic-app." Adjust the name and the command to match your specific project.

    1. Save PM2 Configuration:


    2. pm2 save

    3. This command saves the currently running PM2 processes and their configurations so they will automatically restart after system reboots.


    4. View PM2 Logs:


    5. pm2 logs

    6. This command displays the logs of your running PM2 processes, which can be helpful for troubleshooting.





    1. Resurrect PM2 Processes After a Reboot:

    2.  

    3. pm2 resurrect

    4. This command ensures that your PM2-managed processes are restarted automatically after a system reboot.

Step 3: Install Code Deploy Agent

Step 1: Update Your System

sudo yum update

This command ensures that your system is up to date.

Step 2: Install Ruby, Wget, and Download CodeDeploy Agent

sudo yum install ruby

sudo yum install wget

cd /home/ec2-user

wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install

chmod +x ./install

These commands install Ruby (required for some CodeDeploy scripts), Wget (a command-line utility to download files), and then download the CodeDeploy agent installation script.




Step 3: Install and Configure the CodeDeploy Agent

sudo ./install auto

This command installs the CodeDeploy agent and configures it to start automatically at boot.

Step 4: Check CodeDeploy Agent Status

sudo service codedeploy-agent status



 

This command checks the status of the CodeDeploy agent to ensure it's running correctly.

Step 5: Create appspec.yml

Create an appspec.yml file in the root directory of your project. This file defines how CodeDeploy should deploy your application.

version: 0.0

os: linux

hooks:

ApplicationStart:

- location: deploy.sh

timeout: 300

runas: ec2-user

In this example, we specify that CodeDeploy should run the deploy.sh script during the ApplicationStart deployment event. Adjust the timeout and runas values as needed.

Step 6: Create deploy.sh

Create a deploy.sh script in the root directory of your project. This script should contain the deployment steps for your application.

#!/bin/bash

cd /path/to/your/app

git pull origin main # Replace with your Git branch

npm install

npm run build

pm2 restart my-dynamic-app # Restart your Node.js application 

Replace /path/to/your/app with the actual path to your application's directory. Adjust the Git pull, npm commands, and pm2 restart as needed for your specific project.


Step 7: Make deploy.sh Executable

Make sure the deploy.sh script is executable:

chmod +x deploy.sh

Step 8: Testing Deployment

Now, when you trigger a deployment through AWS CodeDeploy, it will use the appspec.yml and execute the deploy.sh script to deploy your Node.js application.

Remember to customize the deploy.sh script and appspec.yml file to match your project's requirements and directory structure.

Step 4: Configure IAM Roles

  • Create an IAM Role for CodeDeploy:

    1. Access IAM in the AWS Console via the top search bar.
    2. In IAM, go to Roles and click "Create role."
    3. Choose "AWS service" as the trusted entity type and "CodeDeploy" in use cases.
    4. The default AWSCodeDeployRole policy is selected. Proceed.
    5. Name the IAM role descriptively (e.g., "code-deploy-role").
    6. Review the JSON permissions and click "Create role."






  • Create an IAM Role for EC2:

  1. Create another role, this time for EC2.
  2. Choose "AWS service" as the trusted entity type, "EC2" in common use cases, and "CodeDeploy" in use cases for other AWS services.
  3. Add permissions by searching for "codedeploy" (without spaces) and select "AmazonEC2RoleForCodeDeploy."
  4. Review and name the role meaningfully (e.g., "code-deploy-for-ec2"). Click "Create role."


 












        • Attaching the IAM Role to EC2:

          1. To attach the IAM role to an EC2 instance, open the EC2 instance details.
          2. Click "Actions" in the top right, then choose "Security" > "Modify IAM role."
          3. Select the recently created IAM role (e.g., "code-deploy-for-ec2") and click "Update IAM role."
          4. Reboot the EC2 instance for the changes to take effect.





              • Post-Reboot Actions:

                1. After the EC2 instance reboots, SSH into it.
                2. Run the command "pm2 resurrect" to restore PM2 processes.
                3. Failing to do this may lead to a "PM2 Process or Namespace not found error" during automatic deployment.

                          Step 5: Create Code Deploy Application

                            Creating the CodeDeploy Application:
                              1. Access the AWS Console and search for "CodeDeploy" in the top search bar.
                              2. Select "Applications" on the left sidebar.
                              3. Click the "Create application" button in the top-right corner.
                              4. Enter the application name and choose the "EC2/On-premises" compute platform.
                              5. Click "Create application."







                            Creating a Deployment Group:
                              1. After creating the application, you'll be redirected to the Deployment groups section.
                              2. Click on "Create deployment group."
                              3. Enter the deployment group name.
                              4. Select the service role (code-deploy-role) you previously created.
                              5. Choose the deployment type as in-place.
                              6. Under Environment configuration, select "Amazon EC2 instances" and specify the key as "Name." Enter your EC2 instance name as the value.
                              7. In the Agent configuration section, select "Never" since you've already installed CodeDeployAgent.
                              8. For Deployment settings, choose "CodeDeployDefault.AllAtOnce."
                              9. Leave the "Enable load balancing" checkbox unchecked.
                              10. Click "Create a deployment group."
                            Creating the CodePipeline:
                              1. Search for "CodePipeline" in the AWS Console.
                              2. Select "Pipelines" from the left sidebar.
                              3. Click the "Create pipeline" button.
                              4. Enter the pipeline name and role name.
                              5. Note that roles for EC2 and CodeDeploy have already been created.
                              6. AWS will create a role for CodePipeline by default.




                            Adding the Source Stage:
                              1. Connect your repository with CodePipeline to enable automatic deployments.
                              2. Select GitHub (version 2) as the source provider.
                              3. Click "Connect to GitHub" and follow the GitHub authorization process.
                              4. Choose the desired repository and branch.
                              5. Ensure "Start the pipeline on source code change" is checked.
                              6. Select "CodePipeline default" for output and artifact format.
                              7. Click "Next."







                            Adding the Deploy Stage:
                              1. In the deployment stage, choose "AWS CodeDeploy" as the deploy provider.
                              2. Select the appropriate region, application name, and deployment group created earlier.
                              3. Click "Next."




                            Review and Create:
                              1. Review all the configuration settings.
                              2. Click "Create pipeline."
                              3. The pipeline will initiate the deployment process automatically.
                            Verifying Auto-Deployment:
                              1. After making changes to your project and merging them into the main branch on GitHub, the CodePipeline will trigger automatic deployment.
                              2. Check the deployed changes to verify that auto-deployment is functioning correctly.


                              By following these steps, you'll have set up automatic deployments using AWS CodePipeline and AWS CodeDeploy, ensuring that changes pushed to your GitHub repository are automatically deployed to your EC2 instances.


                            Comments