CI/CD Pipeline for Node.js React Application using GitHub Actions on AWS EC2

CI/CD Pipeline for Node.js React Application using GitHub Actions on AWS EC2

Table of Contents:


  1. Launching an AWS EC2 Ubuntu Server
  2. Connecting to the AWS EC2 Instance
  3. Installing Node.js, NPM, and Nginx
  4. Cloning the ReactJS App to EC2
  5. Installing Required Dependencies
  6. Creating a Production Build
  7. Configuring Nginx
  8. Starting the Application
  9. GitHub Actions Self-Hosted Runner
  10. Creating Github actions

Github Repo: https://github.com/codewithmuh/github-actions-cicd-react-aws-ec2/


Step 1: Launch an AWS EC2 Ubuntu Server

  • Log in to the AWS Management Console.
  • Navigate to the EC2 Dashboard.
  • Click on “Launch Instance” and choose an Amazon Machine Image (AMI) with your preferred OS.

Step 2: Connecting to the EC2 Instance

  • Use your preferred SSH terminal to connect to the EC2 instance.
  • For example, if you’re on a Mac, you can use the Terminal app.

Step 3:Install Node, NPM, and Nginx


  • Update the package manager:

sudo apt-get update -y        

  • Install node version 20

curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -        
sudo apt install -y nodejs        

  • Install npm

sudo apt install npm -y        


  • Install the Nginx web server:


sudo apt install nginx -y        

Step 4: Cloning ReactJS App to EC2

For Public Repository:

You can also use my repo: https://github.com/codewithmuh/frontend-react.git

git clone <YOUR-GIT-Repo>        

For Private Repository:

git clone <YOUR-GIT-Repo>        

It will ask you for your GitHub username:

Then Password. You can create a password

Settings-> Developer Settings -> Token>

save the token somewhere, and use it as a password whenever needed.

Step 5: Install all the required dependencies


  • Install dependencies for your React project:

cd <project-folder>
npm install        

Step 6: Create Production Build


  • Build the React app:


npm run build        


  • Create a directory for react


 sudo mkdir -p /var/www/vhosts/frontend/        


  • Copy the “build” folder to the “/var/www/vhosts/frontend” directory so that Nginx can read from this folder.


sudo cp -R build/ /var/www/vhosts/frontend/        

Step 7: Create Nginx File

with this command, you can check if already a default nginx file exists. You have to remove it.

cd /etc/nginx/sites-enabled/

sudo rm -rf default

Create a configuration file for Nginx using the following command

sudo vim /etc/nginx/sites-available/<nginx-file-name>        

Paste the below contents inside the file created

server {
    listen 80 default_server;
    server_name _;

    location / {
        autoindex on;
        root /var/www/vhosts/frontend/build;  # Path frontend build
        try_files $uri /index.html;
    }
}        

Activate the configuration using the following command:

sudo ln -s /etc/nginx/sites-available/<nginx-file-name> /etc/nginx/sites-enabled/        

Run this command to load a static file

$ sudo gpasswd -a www-data <username>


username in my case is ubuntu.

Step 8: Start the Application

Restart Nginx and allow the changes to take place.

sudo systemctl restart nginx
sudo service nginx restart        

Additionally in case of errors

To check error logs

 $ sudo tail -f /var/log/nginx/error.log        

To check if nginx is working fine

$ sudo systemctl status nginx        

One more thing is we have setup the github auth with our ec2, so when we take latest code from the repo, it should not ask for a password.


We can setup it.(this section is explained in the video of this article). This is very important before you move to setup 9.


Step 9: GitHub Actions: Setup Self Hosted runner on Ec2

Now Go to GitHub Repository and click on Settings -> Actions -> Runners

Click on New self-hosted runner

Now select Linux and Architecture X64


Use the below commands to add a self-hosted runner

Note: In pic, Commands are related to my account, Use your commands, they will appear on your GitHub self-hosted runner Page.


Now SSH to your AWS instance to connect with your Instance.

And Past/Run these commands.

mkdir actions-runner && cd actions-run        


Command "mkdir actions-runner && cd actions-runner" serves to generate a fresh directory named "actions-runner" within the present working directory. Subsequently, it swiftly switches the current working directory to this newly created "actions-runner" directory. This approach streamlines file organization and facilitates executing successive actions within the newly formed directory without the need for separate navigation.

Download the latest runner package

curl -o actions-runner-linux-x64-2.311.0.tar.gz -L https://github.com/actions/runner/releases/download/v2.311.0/actions-runner-linux-x64-2.311.0.tar.gz        


Validate the hash.

echo "29fc8cf2dab4c195bb147384e7e2c94cfd4d4022c793b346a6175435265aa278  actions-runner-linux-x64-2.311.0.tar.gz" | shasum -a 256 -c        


Now Extract the installer

tar xzf ./actions-runner-linux-x64-2.311.0.tar.gz        

Create the runner and start the configuration experience

./config.sh --url https://github.com/codewithmuh/react-aws-eks-github-actions --token AMFXNTP3IVE6IAZSWO3ZEGDFT2QV6        


If you have provided multiple labels use commas for each label.

Do not commands except ./run.sh .

Create systemd Service File on EC2.

 sudo nano /etc/systemd/system/run-script.service        

Paste the below content

[Unit]
Description=Script Runner Service
After=network.target

[Service]
Type=simple
Restart=always
User=ubuntu
WorkingDirectory=/home/ubuntu/actions-runner
ExecStart=/home/ubuntu/actions-runner/run.sh

[Install]
WantedBy=multi-user.target        

Run These Scripts.

sudo systemctl daemon-reload 
sudo systemctl enable run-script 
sudo systemctl start run-script 
sudo systemctl status run-script        

Step 10: GitHub Actions File

create a file in your Project

'.github/workflows/cicd.yml'

and then past the content there.

Then Change The Project Name: <Project-Name> Replace with yours.

then push the changes to your main branch via a PR request from feature branch.

name: Deploy

on:
  push:
    branches:
      - main
  pull_request:
    types: [closed]

jobs:
  deploy:
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: self-hosted

    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Build and Deploy
        run: |
          cd /home/ubuntu/<Project-Name>
          git pull origin main
          npm install
          npm run build --production
          sudo cp -R dist/ /var/www/vhosts/frontend/
          sudo service nginx restart        



要查看或添加评论,请登录

社区洞察

其他会员也浏览了