AWS Builder Center
Building an Automated CI/CD Pipeline for Node.js Applications Using AWS CodePipeline

Building an Automated CI/CD Pipeline for Node.js Applications Using AWS CodePipeline

Learn how to automate the build, testing, and deployment of a Node.js application using AWS CodePipeline, AWS CodeBuild, and Amazon EC2. This hands-on guide explains how to create a continuous delivery workflow that deploys application updates whenever new code is pushed to GitHub.

Building an Automated CI/CD Pipeline for Node.js Applications Using AWS CodePipeline

Introduction

Deploying an application manually every time new code is written can become repetitive, time-consuming, and error-prone. In modern software development, teams use Continuous Integration and Continuous Delivery (CI/CD) pipelines to automate the process of building, testing, and deploying applications.
Amazon Web Services provides several developer tools that make this process easier. In this tutorial, we will build an automated CI/CD pipeline for a Node.js application using AWS CodePipeline, AWS CodeBuild, and AWS CodeDeploy.
By the end of this guide, you will have a pipeline that automatically builds and deploys your application to an Amazon EC2 instance whenever changes are pushed to GitHub.

1. Understanding CI/CD

CI/CD is a software development practice that automates the integration, testing, and delivery of application code.
Continuous Integration (CI):
  • Developers regularly push code changes to a shared repository.
  • The system automatically builds the application.
  • Automated tests are executed to identify errors early.
Continuous Delivery/Deployment (CD):
  • Successfully built application code moves through deployment stages.
  • Application updates are deployed to the target environment.
  • Deployment processes become more consistent and repeatable.
A CI/CD pipeline reduces manual work and helps developers deliver software more reliably.

2. AWS Services Used

We will use the following AWS services:
Amazon CodePipeline
AWS CodePipeline manages the CI/CD workflow. It connects different stages of the deployment process, such as source control, building, and deployment.
AWS CodeBuild
AWS CodeBuild is a fully managed build service that compiles source code, runs tests, and prepares application artifacts.
AWS CodeDeploy
AWS CodeDeploy automates application deployments to Amazon EC2 instances. It manages deployment lifecycle events and executes deployment scripts.
Amazon EC2
Amazon EC2 provides the virtual server where our Node.js application will run.
GitHub
GitHub stores the application source code. CodePipeline connects to the repository and detects new commits.

3. Understanding the Architecture

The deployment workflow follows this sequence:
  1. A developer pushes updated code to GitHub.
  1. AWS CodePipeline detects the repository changes.
  1. AWS CodeBuild installs dependencies and runs the build and test commands.
  1. CodeBuild generates a deployment artifact containing the application files and deployment configuration.
  1. AWS CodeDeploy receives the artifact and deploys it to the EC2 instance.
  1. Deployment scripts install production dependencies and restart the Node.js application.
  1. The updated application becomes available to users.
Architecture flow:
GitHub → AWS CodePipeline → AWS CodeBuild → AWS CodeDeploy → Amazon EC2 → Node.js Application

4. Prerequisites

Before starting, make sure you have:
  • An active AWS account.
  • A GitHub account.
  • Basic knowledge of Node.js and Express.js.
  • A Node.js application ready for deployment.
  • An Amazon EC2 instance running Amazon Linux.
  • Basic familiarity with IAM roles and security groups.
For this tutorial, we will use a simple Express application.

5. Create a Node.js Application

First, create a project directory on your local machine.
mkdir aws-cicd-node-app
cd aws-cicd-node-app
npm init -y
Install Express:
npm install express
Create a file named  server.js .
const express = require("express");

const app = express();
const PORT = 3000;

app.get("/", (req, res) => {
res.send("Node.js application deployed successfully using AWS CI/CD!");
});

app.get("/health", (req, res) => {
res.status(200).send("Application is healthy");
});

app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Update the  package.json  file to include a start script.
{
"scripts": {
"start": "node server.js"
}
}
Keep the generated dependencies and package-lock.json file in your project.

6. Push the Application to GitHub

Create a new repository on GitHub.
Initialize Git in your project directory:
git init
git add .
git commit -m "Initial Node.js application"
git branch -M main
git remote add origin YOUR_GITHUB_REPOSITORY_URL
git push -u origin main
Your application source code is now available in GitHub.

7. Launch and Configure an EC2 Instance

Open the AWS Management Console and navigate to Amazon EC2.
Follow these steps:
  1. Select Launch Instance.
  1. Enter an instance name, such as  nodejs-cicd-server .
  1. Choose an Amazon Linux AMI.
  1. Select an instance type suitable for your workload.
  1. Configure a key pair for secure access.
  1. Create or select a security group.
Configure the inbound security group rules:
Type
Port
Source
SSH
22
Your IP address
Custom TCP
3000
Your IP address for testing
For a production deployment, use a reverse proxy such as Nginx and expose HTTP/HTTPS ports 80 and 443 instead of exposing the Node.js port directly.
Launch the instance and connect to it using SSH.

8. Prepare the EC2 Instance

Connect to your EC2 instance and update the system packages.
sudo dnf update -y
Install Node.js and npm using an appropriate supported installation method for your Amazon Linux version.
Verify the installation:
node -v
npm -v
Install PM2 globally:
sudo npm install -g pm2
PM2 is a process manager that helps keep Node.js applications running in the background and restart them when necessary.

Install and Configure the CodeDeploy Agent

The CodeDeploy agent is required on EC2 instances to receive and execute deployments.
Install the agent using the official AWS instructions for your EC2 operating system and AWS Region.
After installation, start and enable the service:
sudo systemctl start codedeploy-agent
sudo systemctl enable codedeploy-agent
Check its status:
sudo systemctl status codedeploy-agent
The agent must be running before you proceed with deployment.

9. Configure IAM Roles

IAM roles allow AWS services and EC2 instances to communicate securely without storing access keys in application code.
You need to configure the following roles:
CodePipeline service role
  • Allows CodePipeline to access the connected source, build, and deployment services.
CodeBuild service role
  • Allows CodeBuild to access the required build resources and upload artifacts.
CodeDeploy service role
  • Allows CodeDeploy to manage deployments to EC2 instances.
EC2 instance profile
  • Allows the CodeDeploy agent to communicate with AWS services and access deployment artifacts.
Use the appropriate AWS-managed policies or narrowly scoped custom policies. Avoid granting unnecessary administrator permissions.
Attach the required EC2 instance profile to your EC2 instance.

10. Create the Deployment Configuration

CodeDeploy requires an  appspec.yml  file to understand how application files should be copied and which scripts should run during deployment.
Create the following project structure:
aws-cicd-node-app/
│
├── server.js
├── package.json
├── package-lock.json
├── buildspec.yml
├── appspec.yml
│
└── scripts/
├── before_install.sh
├── after_install.sh
├── start_application.sh
└── validate_service.sh
Create  appspec.yml :
version: 0.0
os: linux

files:
- source: /
destination: /var/www/nodejs-app

hooks:
ApplicationStop:
- location: scripts/before_install.sh
timeout: 60
runas: root

AfterInstall:
- location: scripts/after_install.sh
timeout: 300
runas: root

ApplicationStart:
- location: scripts/start_application.sh
timeout: 120
runas: root

ValidateService:
- location: scripts/validate_service.sh
timeout: 60
runas: root
These lifecycle hooks control what happens during deployment.

Create the Deployment Scripts

Create  scripts/before_install.sh :
#!/bin/bash

if id ec2-user >/dev/null 2>&1; then
sudo -u ec2-user pm2 delete nodejs-app || true
fi

mkdir -p /var/www/nodejs-app
Create  scripts/after_install.sh :
#!/bin/bash

cd /var/www/nodejs-app

npm ci --omit=dev

chown -R ec2-user:ec2-user /var/www/nodejs-app
Create  scripts/start_application.sh :
#!/bin/bash

cd /var/www/nodejs-app

sudo -u ec2-user pm2 startOrReload ecosystem.config.js --update-env
sudo -u ec2-user pm2 save
Create  ecosystem.config.js  in the project root:
module.exports = {
apps: [{
name: "nodejs-app",
script: "server.js",
instances: 1,
autorestart: true,
watch: false
}]
};
Create  scripts/validate_service.sh :
#!/bin/bash

sleep 5

curl --fail http://localhost:3000/health
Make sure the deployment scripts have executable permissions:
chmod +x scripts/*.sh
The deployment scripts assume that PM2 is installed globally and that the application runs as  ec2-user .

11. Configure AWS CodeBuild

Now we will configure CodeBuild to install dependencies and execute the build process.
Create a file named  buildspec.yml  in your project root.
version: 0.2

phases:
install:
runtime-versions:
nodejs: 20
commands:
- echo Installing dependencies
- npm ci

build:
commands:
- echo Running application tests
- npm test --if-present
- echo Build completed successfully

artifacts:
files:
- '**/*'
exclude-paths:
- node_modules/**/*
The build specification defines the commands executed by CodeBuild.
What happens here?
  • The install phase selects the Node.js runtime and installs dependencies.
  • The build phase executes available tests.
  • The artifacts section prepares the application files for deployment without including the local  node_modules  directory.
In the AWS Management Console:
  1. Open AWS CodeBuild.
  1. Select Create build project.
  1. Enter a project name.
  1. Connect the GitHub source repository.
  1. Choose a managed build environment.
  1. Select a supported Node.js runtime.
  1. Configure the CodeBuild service role.
  1. Select the buildspec file from the repository.
  1. Create the build project.
The build project is now ready to be used by CodePipeline.

12. Configure AWS CodeDeploy

Open AWS CodeDeploy in the AWS Management Console.
Create an application:
  1. Select Create application.
  1. Enter an application name such as  nodejs-cicd-app .
  1. Choose EC2/On-premises as the compute platform.
Next, create a deployment group.
  1. Enter a deployment group name.
  1. Select the CodeDeploy service role.
  1. Choose the EC2 deployment environment.
  1. Select the EC2 instance using its tags.
  1. Configure the deployment settings.
  1. Create the deployment group.
Ensure that your EC2 instance has the correct instance profile and that the CodeDeploy agent is running.

13. Create the AWS CodePipeline

Now connect all the services into one automated workflow.
Open AWS CodePipeline and select Create pipeline.

Stage 1: Source

  • Enter a pipeline name.
  • Select GitHub through AWS CodeConnections.
  • Authorize the GitHub connection.
  • Select your repository.
  • Select the  main  branch.
  • Enable change detection.
This stage detects new commits pushed to the selected branch.

Stage 2: Build

  • Select AWS CodeBuild as the build provider.
  • Choose the build project created earlier.
  • Configure the input artifact from the source stage.
  • Save the configuration.
CodeBuild now installs dependencies and runs the configured tests.

Stage 3: Deploy

  • Select AWS CodeDeploy as the deployment provider.
  • Choose the CodeDeploy application.
  • Select the deployment group.
  • Use the artifact generated by the build stage.
Review the pipeline configuration and create the pipeline.
Your automated CI/CD pipeline is now configured.

14. Test the Automated Deployment

It is time to verify the complete workflow.
Make a small change to your  server.js  file.
For example:
app.get("/about", (req, res) => {
res.send("This application is deployed through AWS CodePipeline!");
});
Push the changes to GitHub:
git add .
git commit -m "Add about endpoint"
git push origin main
Now open AWS CodePipeline.
You should observe the following stages:
  1. Source stage detects the new commit.
  1. Build stage executes the CodeBuild commands.
  1. Deploy stage starts the CodeDeploy deployment.
  1. CodeDeploy executes the lifecycle scripts on EC2.
Once all stages succeed, access your application using:
http://YOUR_EC2_PUBLIC_IP:3000/about
You should see the updated response.
This confirms that the application has been updated through the automated pipeline.

15. Monitoring and Troubleshooting

Monitoring is important because deployment failures can occur at different stages.
CodePipeline
  • Check the status of each pipeline stage.
  • Identify which stage failed.
  • Review the associated error messages.
CodeBuild
  • Open the build execution details.
  • Inspect build logs.
  • Check dependency installation and test failures.
CodeDeploy
  • Review deployment lifecycle events.
  • Inspect failed scripts and deployment logs.
  • Verify the CodeDeploy agent status.
Common CodeDeploy agent log location:
/var/log/aws/codedeploy-agent/codedeploy-agent.log
For application logs, use PM2:
pm2 logs nodejs-app
For production environments, Amazon CloudWatch can also be configured to collect and monitor application and deployment-related logs.

16. Best Practices

Consider the following practices when implementing CI/CD pipelines:
  • Use IAM roles with least-privilege permissions.
  • Never store AWS access keys or passwords in source code.
  • Keep environment variables and secrets outside the GitHub repository.
  • Run automated tests before deploying application updates.
  • Use separate development, testing, and production environments.
  • Configure deployment health checks.
  • Monitor application logs and deployment failures.
  • Use HTTPS for production application traffic.
  • Configure rollback strategies for unsuccessful deployments.
  • Regularly update dependencies and server packages.

Conclusion

Automating Node.js application deployment using AWS CodePipeline, CodeBuild, and CodeDeploy provides a structured approach to continuous integration and continuous delivery.
By connecting GitHub with AWS developer tools, developers can automate code integration, dependency installation, testing, and application deployment to Amazon EC2.
This approach reduces repetitive manual deployment tasks, improves consistency, and provides a foundation for building scalable DevOps workflows.
Understanding CI/CD pipelines is an important step toward modern cloud application development and production deployment.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article