AWS Builder Center
Build a CI/CD Pipeline on AWS with CodePipeline, CodeBuild, ECR and ECS (Fargate)

Build a CI/CD Pipeline on AWS with CodePipeline, CodeBuild, ECR and ECS (Fargate)

A beginner-friendly, hands-on guide to automating build and deployment of a Dockerized app on AWS. Push to GitHub and watch CodePipeline, CodeBuild and ECS ship it for you, with an EC2 alternative, cost notes and cleanup steps.

Technology Enthusiast | AI & Cloud Explorer | Hackathoner | Problem Solver

Introduction

Manually building, testing and deploying an app gets old fast. A CI/CD pipeline automates all of it: every time you push code, it is built, packaged and deployed without you touching the console.
In this article, we build a complete pipeline using native AWS services:
  • AWS CodePipeline orchestrates the stages
  • AWS CodeBuild builds the Docker image
  • Amazon ECR stores the image
  • Amazon ECS (Fargate) runs the container
At the end, I also cover how to target EC2 instead of ECS.

What You'll Learn

  • How the pieces of an AWS CI/CD pipeline fit together
  • How to write a  buildspec.yml  that builds and pushes a Docker image
  • How to wire GitHub, CodeBuild and ECS into one automated flow
  • How to troubleshoot the most common pipeline failures
  • How to clean up so you don't get surprise bills

Prerequisites

  • An AWS account (Free Tier helps, but Fargate and NAT/ALB resources are not free)
  • A GitHub repository with a simple app and a  Dockerfile 
  • Basic Docker knowledge
  • AWS CLI configured (optional, but handy)

Architecture Overview

Developer -> GitHub -> CodePipeline
|
[Source] -> [Build: CodeBuild] -> [Deploy: ECS]
| |
Amazon ECR <----- ECS Service (Fargate)
  1. A push to GitHub triggers CodePipeline.
  1. CodeBuild builds the Docker image, tags it with the commit ID and pushes it to ECR.
  1. CodeBuild outputs  imagedefinitions.json , which tells ECS which image to run.
  1. The ECS deploy action updates the service with a rolling deployment.
Add your own architecture diagram here as an uploaded image.

Step-by-Step Implementation

Step 1: Prepare the application

A minimal  Dockerfile  for a Node.js app:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Commit it to your GitHub repo along with your app code.

Step 2: Create an ECR repository

aws ecr create-repository --repository-name my-app --region ap-south-1
Note the repository URI, for example  123456789012.dkr.ecr.ap-south-1.amazonaws.com/my-app .

Step 3: Create the ECS cluster, task definition and service

  1. Open ECS and create a cluster using AWS Fargate.
  1. Create a task definition (Fargate) with one container:
  • Container name:  my-app  (remember this, you'll need it later)
  • Image: your ECR URI with a placeholder tag such as  :latest 
  • Port mapping:  3000 
  1. Create a service from the task definition with the desired count set to  1 .
  1. Make sure the security group allows inbound traffic on your app port.
The task execution role should include  AmazonECSTaskExecutionRolePolicy  so ECS can pull images from ECR.

Step 4: Add a  buildspec.yml  to your repository root

version: 0.2

phases:
pre_build:
commands:
- echo Logging in to Amazon ECR...
- aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
- IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
build:
commands:
- echo Building the Docker image...
- docker build -t $REPOSITORY_URI:$IMAGE_TAG .
post_build:
commands:
- echo Pushing the Docker image...
- docker push $REPOSITORY_URI:$IMAGE_TAG
- echo Writing image definitions file...
- printf '[{"name":"%s","imageUri":"%s"}]' $CONTAINER_NAME $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json

artifacts:
files:
- imagedefinitions.json
Why tag with the commit ID? Every deployment is traceable to an exact commit, and rollbacks are simple. Avoid relying on  latest  alone.

Step 5: Create the CodeBuild project

  1. Open CodeBuild and create a build project.
  1. Source: connect to your GitHub repo (or let CodePipeline supply the source).
  1. Environment: managed image, Amazon Linux, standard runtime.
  1. Enable "Privileged". This is required to run Docker builds.
  1. Add environment variables:
Name
Value
 AWS_ACCOUNT_ID 
your 12-digit account ID
 REPOSITORY_URI 
your full ECR repository URI
 CONTAINER_NAME 
 my-app  (must match the task definition)
  1. Attach ECR permissions to the CodeBuild service role, for example  AmazonEC2ContainerRegistryPowerUser , or a tighter custom policy.

Step 6: Create the pipeline in CodePipeline

  1. Source stage: choose GitHub (via GitHub App), authorize the connection, then select your repo and branch.
  1. Build stage: choose AWS CodeBuild and select the project from Step 5.
  1. Deploy stage: choose Amazon ECS, then select your cluster and service. Set the image definitions file to  imagedefinitions.json .
  1. Review and create the pipeline.
The first run starts automatically.

Step 7: Trigger the pipeline

Make a small change, commit and push:
git add .
git commit -m "Update homepage text"
git push origin main
Open the pipeline and watch Source, Build and Deploy turn green in turn.

Alternative: Deploying to EC2 instead of ECS

If you prefer virtual machines:
  1. Launch an EC2 instance and install the CodeDeploy agent.
  1. Attach an instance profile that allows the agent to read from S3.
  1. Add an  appspec.yml  and lifecycle scripts ( BeforeInstall ,  AfterInstall ,  ApplicationStart ) to your repo.
  1. In CodePipeline, use AWS CodeDeploy as the deploy provider and point it at your application and deployment group.
  1. Let CodeBuild output your application bundle as an artifact instead of  imagedefinitions.json .
ECS is a better fit for containers and removes server management. EC2 with CodeDeploy gives you more control over the machine.

Testing and Results

After a successful run, check:
  • ECR: a new image tagged with the 7-character commit ID
  • ECS service: a new task running the updated task definition revision
  • Your app URL: the change you pushed is live

Common Issues and Fixes

Problem
Likely cause
Fix
 Cannot connect to the Docker daemon 
Privileged mode is off
Enable it in the CodeBuild environment
 no basic auth credentials  on push
Missing ECR login or permissions
Check the login command and the role policy
Deploy stage fails on  imagedefinitions.json 
Container name mismatch
Make  CONTAINER_NAME  match the task definition exactly
ECS tasks keep restarting
App crash or failing health check
Check CloudWatch Logs and the port mapping

Cost and Cleanup

Main cost drivers: Fargate task runtime, CodeBuild build minutes, CodePipeline (one active pipeline may be covered by the free tier, so check current pricing), ECR storage, and a load balancer or NAT gateway if you add one.
To clean up:
  1. Delete the pipeline in CodePipeline
  1. Delete the CodeBuild project
  1. Set the ECS service desired count to  0 , then delete the service and cluster
  1. Delete the ECR repository (and images)
  1. Remove unused IAM roles and CloudWatch log groups

Best Practices

  • Use least-privilege IAM roles for CodeBuild and CodePipeline
  • Store secrets in AWS Secrets Manager or SSM Parameter Store, never in the repo
  • Add a test phase to  buildspec.yml  so bad code fails before deploying
  • Add a manual approval stage before production deployments
  • Enable ECS deployment circuit breaker for automatic rollback on failed deployments

Conclusion

With CodePipeline, CodeBuild, ECR and ECS, you get a fully managed path from  git push  to a running container. From here you can add automated tests, a staging environment, approval gates and blue/green deployments with CodeDeploy.
If you found this useful, share your own pipeline setup in the comments.


Written as part of my journey as an AWS Student Builder.
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