Automated Node.js Deployment to AWS EC2 with Docker and GitHub Actions

VENKATA SRI HARI - Jul 28 - - Dev Community

In this project, we will learn how to deploy a Node.js application using GitHub Actions, Docker, and AWS EC2. This fully automated pipeline ensures that our application on the EC2 instance is always up-to-date with the latest changes.

GitHub Actions is a CI/CD platform designed to automate your build, test, and deployment processes. By configuring a .yml file, you can specify tasks to run in response to events like pull requests, issues, or commits.

In this guide, we will utilize GitHub Actions to build a Docker image and push it to Docker Hub. An AWS EC2 instance will serve as a self-hosted runner. The instance will then pull and run the Docker container, allowing us to access the application via its public IP.

Image description
Github link: NodeJS-Deployment

  1. let’s create a Dockerfile in the project’s root directory.

Image description
You can use this same docker file in your project also….


Enter fullscreen mode Exit fullscreen mode
  1. Now I can create a .dockerignore file.

Image description

# dockerignore file 
node_modules/
package-lock.json
Enter fullscreen mode Exit fullscreen mode
  1. Log in to GitHub account and create a new repository and{My Repository Name is NodeJS-Deployment, in you case you can choose different name}.

Image description
click on create Repository.

  1. Push your existing code to the GitHub repository.

Image description
Give this below cmds

git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/Consultantsrihari/NodeJS-Deployment
git push -u origin main
Enter fullscreen mode Exit fullscreen mode

Image description

  1. Now go toActions tab and select Docker image and click on Configure, then you can write the docker .yml file.

Image description

Image description
In your case write own docker image or you can use below code.

# Name of the GitHub Actions workflow
name: CI/CD for Node.js REST-API

# Trigger this workflow on push events to the main branch and manual dispatch
on:
  push: 
    branches: [main]
  workflow_dispatch:

# Permissions needed for this workflow
permissions:
  contents: write

# Define the jobs to be executed
jobs:
  # Build job
  Build:
    # Use the latest Ubuntu runner
    runs-on: ubuntu-latest

    # Steps to be executed in the Build job
    steps:
      # Checkout the repository
      - name: Checkout repository
        uses: actions/checkout@v3 

      # Login to DockerHub using secrets for credentials
      - name: Login to DockerHub
        env:
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
        run: echo $DOCKER_PASSWORD | docker login -u $DOCKER_USERNAME --password-stdin

      # Build Docker image with a specific tag
      - name: Build Docker Image
        run: docker build -t bishal5438/rest-api .

      # Push the built image to DockerHub
      - name: Push to DockerHub
        run: docker push bishal5438/rest-api:latest 

  # Deploy job
  Deploy:
    # Use a self-hosted runner for deployment
    runs-on: self-hosted

    # Steps to be executed in the Deploy job
    steps:
      # Pull the latest Docker image from DockerHub
      - name: Pull the Docker Image
        run: docker pull bishal5438/rest-api:latest 

      # Delete the old container if it exists
      - name: Delete Old Container
        run: |
          if [ "$(docker ps -q -f name=rest-api-Container)" ]; then
            sudo docker rm -f rest-api-Container
          fi

      # Run a new container from the pulled image
      - name: Run the Container
        run: docker run -d -p 80:80 --name rest-api-Container bishal5438/rest-api
Enter fullscreen mode Exit fullscreen mode

Now, commit the changes, which will create a CI-CD docker-image.yml file inside .github/workflows

Image description

  1. Now, let’s configure GitHub secrets to store sensitive information such as Docker Hub’s username and password.

For this, go to the repositorySettings

Click onSecrets and variables and select Actions.

Image description

  1. To add a new secret, click on New repository secret.

Image description

  1. Add your Docker Hub username and password.

Image description

  1. Let’s configure AWS EC2.
  • Go to the AWS console and select EC2 service.
  • Provide an instance name NodeJS-Deployment
  • For the AMI option, select Ubuntu.
  • Select an instance type based on your requirements. I am usingt2.micro instance.
  • For the Key pair option, click on Create new key pair.
  • Provide a key pair name and select RSA as key pair type.
  • Select .pem as private key file format and click on Create key pair.
  • Save the key securely as we need it to connect to our instance.
  • Under Network Settings, click on Create security group.
  • Then, allow http, https and ssh traffic.
  • Select the required volume of storage.
  • Finally click on Launch Instance.
  • Let’s configure AWS EC2.

  • Go to the AWS console and select EC2 service.

  • Provide an instance name NodeJS-Deployment

  • For the AMI option, select Ubuntu.

  • Select an instance type based on your requirements. I am usingt2.micro instance.

  • For the Key pair option, click on Create new key pair.

  • Provide a key pair name and select RSA as key pair type.

  • Select .pem as private key file format and click on Create key pair.

  • Save the key securely as we need it to connect to our instance.

  • Under Network Settings, click on Create security group.

  • Then, allow http, https and ssh traffic.

  • Select the required volume of storage.

  • Finally click on Launch Instance.

Image description

  • Take the public IP of your instance and login.

  • Iam using Git bash, in your case use your own terminal.

  • Now succuesfully login our instance.

Image description

  1. To configure and run docker as a non-root user, use the following commands.

Image description

sudo apt update 

sudo apt install docker.io -y 

#Add group named docker
sudo groupadd docker

#Add user to the docker group 
sudo usermod -aG docker $USER

#Reload group permissions  
newgrp docker

#Managing permission 
sudo chown -R $USER:docker /var/run/docker
sudo chown $USER:docker /var/run/docker.sock

#Restart docker service 
sudo systemctl restart docker 

#Auto start on boot 
 sudo systemctl enable docker

#To check docker status
 sudo systemctl status docker
Enter fullscreen mode Exit fullscreen mode
  1. Now, let’s set up a self-hosted runner for our GitHub repository.

Go to repository Settings.

Click on Actions and select Runners.

Next, click on New self-hosted runner.

Image description

  1. Select Linux as our EC2 instance is based on Ubuntu.

GitHub will provide us the instructions to set up the runner.

Image description

Copy past all cmds in ubuntu server.

Download

# Create a folder
$ mkdir actions-runner && cd actions-runnerCopied!
# Download the latest runner package
$ curl -o actions-runner-linux-x64-2.317.0.tar.gz -L https://github.com/actions/runner/releases/download/v2.317.0/actions-runner-linux-x64-2.317.0.tar.gzCopied!
# Optional: Validate the hash
$ echo "9e883d210df8c6028aff475475a457d380353f9d01877d51cc01a17b2a91161d  actions-runner-linux-x64-2.317.0.tar.gz" | shasum -a 256 -cCopied!
# Extract the installer
$ tar xzf ./actions-runner-linux-x64-2.317.0.tar.gzCopied!

Configure

# Create the runner and start the configuration experience
$ ./config.sh --url https://github.com/Consultantsrihari/NodeJS-Deployment --token BGHFMQ3HYQU6CX2VVFG73E3GUUQJKCopied!
# Last step, run it!
$ ./run.shCopied! 

Using your self-hosted runner
# Use this YAML in your workflow file for each job
runs-on: self-hosted
Enter fullscreen mode Exit fullscreen mode

Image description
If prompted for any inputs, you may press Enter for default values.

  1. Once the setup is completed, we can see active machines under Runners tab on our github repository.

Image description

  1. Now, pull the changes to the remote repo to test CI-CD pipeline, We can see successful and failed jobs under the same action tab.

Image description

  1. Finally, we can access our application by visiting http://.

Image description

Conclusion
Hence, By integrating Github Actions with Docker and AWS, we can automate CI-CD steps and ensure a smooth and reliable workflow for Node.js application.

You’re welcome! Have a great time ahead! Enjoy your day!

Please Connect with me any doubts.

LinkedIn: www.linkedin.com/in/

Mail: sriharimalapati6@gmail.com

GitHub: https://github.com/Consultantsrihari

Thanks for watching ##### %%%% Sri Hari %%%%

Github Actions
Github
Docker
Devops Project
DevOps

.
Terabox Video Player