Next JS CI CD in AWS

Next JS CI CD in AWS

A Comprehensive Guide to Setting up Node.js, Automating CI/CD for NEXT JS with AWS CodePipeline, and Ensuring Smooth Deployments with CodeDeploy

Introduction

In this article, we will walk through the process of setting up a robust Continuous Integration and Continuous Deployment (CI/CD) pipeline for a Next.js application on Amazon Web Services (AWS). This pipeline will automate the building, and deployment of your Next.js app, ensuring a seamless and efficient development workflow.

Prerequisites

Before we begin, make sure you have the following:

  • AWS account (running EC2 Preferably Ubuntu)

  • GitHub account

Steps

  1. Install NodeJS

  2. Install PM2

  3. Create, Run, and Update Next Manually

  4. Brief AWS CI CD Services

  5. Create AWS codePipeline

  6. create Github connection

  7. Creating build Stage

  8. Update the CodeBuild Yaml for the Next JSe (IAM Role ) for AWS EC2

  9. Create IAM Role for AWS CodeDeploy

  10. Create AWS CodeDeploy Application and Deployment Group

  11. Install CodeDeploy Agent in EC2 Ubuntu

  12. Create and Attach IAM for EC2

  13. Update the CodePipeline for adding the Deployment Stage

  14. Discussing Error

  15. What is the Appspec File?

  16. How AWS CodeDeploy works?

I have installed Node js in my EC2 Ubuntu, if you don't you can do it with the following command

Install NodeJS

Download and import the Nodesource GPG key

sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg

Create deb repository

# you can change node version
NODE_MAJOR=20
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$NODE_MAJOR.x nodistro main" | sudo tee /etc/apt/sources.list.d/nodesource.list

Run Update and Install

sudo apt-get update
sudo apt-get install nodejs -y

Create, Run, and Update Next JS Manually

created a sample Next js in Ubuntu 22.04

npx create-next-app nextapp

Let's first manually build this application in EC2 with

npx run build

pm2 start npm --name 'app-with-nginx-proxy' --  run start

Install PM2

why PM2 ?

PM2 is used to manage and run applications in a production environment, providing features such as process management, automatic restarts, and monitoring to ensure high availability and reliability.

npm i -g pm2

start the Application

Make sure you are running this command inside the Next JS project root.

pm2 start npm --name 'app-with-nginx-proxy' --  run start

now start the same application with pm2

Verify application is running in the Server IP address at PORT 3000

let's manually make a change by editing src/app/page.js in application

If you visit your browser this change will not reflect the event restart the application

after remaking the build and restarting pm2, our changes are reflected correctly,

so here we have identified the pattern that we need to run

# Inside the project directory
npm run build
# Restart Pm2 specific application or reload everything
pm2 reload all

I am pushing the initial code to GitHub, if you are following along create a GitHub repo in Github, create a token, and use your token to Push the code in Github

so now I have my Next JS on Github, whenever I make a change and push code to GitHub, I want a way to automatically run a build on changes and restart PM2 after the build.

Note: we will be using the AWS services.

AWS CI CD Services

AWS code pipeline: AWS CodePipeline automates the continuous integration and delivery (CI/CD) process.

AWS CodeBuild: CodeBuild compiles and builds code artifacts;

AWS code deploy: CodeDeploy automates code deployments to various AWS compute services.

Working

Open the CodePipeline console at http://console.aws.amazon.com/codesuite/codepipeline/home

Create AWS codepipeline

Create GitHub Connection for AWS

After the above steps, Your GitHub connection is ready for use.

Creating build Stage

Give project build configuration

AWS CodeBuild needs Service Role for Running Build and Communicating to other services

Configure Logging for Build (Useful)

Successfully created mynextbuildpipeline in CodeBuild.

Skipping Deploy Stage for the time being

Update the CodeBuild Yaml for the Next JS

version: 0.2

phases:
  install:
    runtime-versions:
      nodejs: 18
  build:  
    commands:
      - npm install
      - npm run build

artifacts:
     base-directory: .next
    files:
      - '**/*'

Create IAM Role for AWS CodeDeploy

We need to create the application and Deployment group for AWS CodeDeploy before AWS CodeDeploy needs an IAM Role, so first let's create an IAM role

CodeDeploy needs Permission (IAM Role) to execute scripts and deploy your Application changes to EC2,

because we are Creating a role for CodeDeploy which will deploy changes to EC2 That is why I am choosing the first use case,

Create Application And Deployment Group

creating deployment Group.

Make sure to select the IAM rule you created in the previous steps

Install CodeDeploy Agent in EC2 Ubuntu

you can follow docs.aws.amazon.com/codedeploy/latest/userg..

sudo apt update && sudo apt install ruby-full wget
cd /home/ubuntu
# CHANGE region code if your EC2 is not in us-east-1 ,  you can see in instance
# availibity zone 
wget https://aws-codedeploy-us-east-1.s3.us-east-1.amazonaws.com/latest/install
chmod +x ./install
sudo ./install auto
sudo service codedeploy-agent status

Create EC2 Instance Profile (IAM Role ) for AWS EC2

Attach EC2 Instance Profile (IAM Role ) for CodeDeploy

Please go to your EC2 dashboard and select your EC2

Restart the code Deploy Agent in your EC2

sudo service codedeploy-agent restart

Adding Deployment Step in CodePipeline

Update Codepipleine

Add a new Action Deploy

Note: Choose the input artifact as BuildArtifact, which means the results of the code build will be the input of CodeDeploy

Now make a change in code, I am changing from GitHub Desktop

Note: Please make sure you have included the below appspec.yml file in your Project root

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/nextapp
file_exists_behavior: OVERWRITE
hooks:
  ApplicationStart:
    - location: scripts/start_app.sh
      timeout: 300
      runas: ubuntu

what is the Appspec File?

CodeDeploy uses an AppSpec file to manage each deployment as a series of lifecycle event hooks, which are defined in the file.

How AWS CodeDeploy work?

These changes should trigger the AWS Code pipeline, if not please make sure that you committed in the same branch that is set in the AWS codePipeline

our application changes have been reflected in our application,

That's it,

Troubleshooting

if your application deployment fails with the following error

Script at specified location: scripts/start_app.sh run as user root failed with exit code 1

make sure you set runas: ubuntu in ApplicationStart the section in appspec with the same user as you did manually in the terminal.

Also Please modify the destination of the application according to your Destination in Appsec yaml

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/nextapp
file_exists_behavior: OVERWRITE
hooks:
  ApplicationStart:
    - location: scripts/start_app.sh
      timeout: 300
      runas: ubuntu

If the deployment failed because a specified file already exists at this location:

please make sure you have file_exists_behavior: OVERWRITE is set to your app spec.yaml

version: 0.0
os: linux
files:
  - source: /
    destination: /home/ubuntu/nextapp
file_exists_behavior: OVERWRITE
hooks:
  ApplicationStart:
    - location: scripts/start_app.sh
      timeout: 300
      runas: ubuntu

Did you find this article valuable?

Support Muhammad Usama by becoming a sponsor. Any amount is appreciated!