
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.
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.ymlthat 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)- A push to GitHub triggers CodePipeline.
- CodeBuild builds the Docker image, tags it with the commit ID and pushes it to ECR.
- CodeBuild outputs
imagedefinitions.json, which tells ECS which image to run.
- 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-alpineWORKDIR /appCOPY package*.json ./RUN npm ci --omit=devCOPY . .EXPOSE 3000CMD ["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-1Note 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
- Open ECS and create a cluster using AWS Fargate.
- 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
- Create a service from the task definition with the desired count set to
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.jsonWhy 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
- Open CodeBuild and create a build project.
- Source: connect to your GitHub repo (or let CodePipeline supply the source).
- Environment: managed image, Amazon Linux, standard runtime.
- Enable "Privileged". This is required to run Docker builds.
- 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) |
- Attach ECR permissions to the CodeBuild service role, for example
AmazonEC2ContainerRegistryPowerUser, or a tighter custom policy.
Step 6: Create the pipeline in CodePipeline
- Source stage: choose GitHub (via GitHub App), authorize the connection, then select your repo and branch.
- Build stage: choose AWS CodeBuild and select the project from Step 5.
- Deploy stage: choose Amazon ECS, then select your cluster and service. Set the image definitions file to
imagedefinitions.json.
- 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 mainOpen the pipeline and watch Source, Build and Deploy turn green in turn.
Alternative: Deploying to EC2 instead of ECS
If you prefer virtual machines:
- Launch an EC2 instance and install the CodeDeploy agent.
- Attach an instance profile that allows the agent to read from S3.
- Add an
appspec.ymland lifecycle scripts (BeforeInstall,AfterInstall,ApplicationStart) to your repo.
- In CodePipeline, use AWS CodeDeploy as the deploy provider and point it at your application and deployment group.
- 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:
- Delete the pipeline in CodePipeline
- Delete the CodeBuild project
- Set the ECS service desired count to
0, then delete the service and cluster
- Delete the ECR repository (and images)
- 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.ymlso 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.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article