AWS Builder Center
Build a Production-Ready CI/CD Pipeline on AWS with CodePipeline, CodeBuild, ECR and ECS Fargate

Build a Production-Ready CI/CD Pipeline on AWS with CodePipeline, CodeBuild, ECR and ECS Fargate

A hands-on guide to automating build, test, approval and deployment of a containerized application on AWS, with a working buildspec, IAM guidance and rollback strategy.

CI/CD pipeline on AWS: Source, Build, Test, Deploy
Shipping code by hand works until it doesn't. A forgotten test, a wrong environment variable, or a "quick fix" pushed straight to production is how most outages begin. A CI/CD pipeline removes that risk by making every release follow the same automated, repeatable path.
In this article, you will build a complete pipeline on AWS that takes code from a Git repository to a running container on Amazon ECS with AWS Fargate. By the end, you will understand how each service fits, how to write the build specification, how to secure the pipeline, and how to choose a deployment strategy.
What you'll learn
  • The difference between continuous integration, continuous delivery and continuous deployment
  • How AWS CodePipeline, CodeBuild, Amazon ECR and Amazon ECS work together
  • How to write a  buildspec.yml  that tests, builds and pushes a Docker image
  • How to add a manual approval gate and automatic rollback
  • Security and cost practices you should apply from day one
Prerequisites
  • An AWS account and basic familiarity with the console
  • A GitHub repository containing an application with a  Dockerfile  (this guide uses a Java Spring Boot service, but the pattern works for any language)
  • An existing ECS cluster and Fargate service behind an Application Load Balancer



1. CI, CD and CD: three terms, one pipeline

Term
What it means
In this pipeline
Continuous Integration
Every commit is built and tested automatically
CodeBuild runs unit tests
Continuous Delivery
Every passing build is ready to release, with a human decision
Manual approval stage
Continuous Deployment
Every passing build is released automatically
Remove the approval stage
Most teams start with continuous delivery and move to continuous deployment once their test coverage earns trust.

2. Architecture overview

End-to-end pipeline architecture
The flow is straightforward:
  1. A developer pushes code to GitHub.
  1. AWS CodePipeline detects the change through a connection created with AWS CodeConnections and starts a new execution.
  1. AWS CodeBuild runs tests, builds the Docker image and pushes it to Amazon ECR.
  1. An optional manual approval action notifies reviewers through Amazon SNS.
  1. CodePipeline updates the Amazon ECS service, and Fargate starts the new tasks behind the load balancer.
Each service has one job. CodePipeline orchestrates, CodeBuild executes, ECR stores artifacts, and ECS runs them.

3. What happens in each stage

Details of the Source, Build, Approve and Deploy stages

Stage 1: Source

Create a connection to GitHub from the Developer Tools > Settings > Connections page, then select your repository and the  main  branch as the pipeline source. Every push to that branch triggers an execution.

Stage 2: Build and test

Create a CodeBuild project with these settings:
  • Environment image: the latest Amazon Linux standard image
  • Privileged mode: enabled (required to run Docker builds)
  • Service role: a dedicated role, covered in the security section below
Then add this  buildspec.yml  to the root of your repository:
yaml
version: 0.2

env:
variables:
AWS_REGION: ap-south-1
ECR_REPO: my-app
CONTAINER_NAME: my-app

phases:
pre_build:
commands:
- ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
- REGISTRY=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
- aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $REGISTRY
- IMAGE_TAG=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c1-7)
build:
commands:
- mvn -B test
- docker build -t $REGISTRY/$ECR_REPO:$IMAGE_TAG .
post_build:
commands:
- docker push $REGISTRY/$ECR_REPO:$IMAGE_TAG
- printf '[{"name":"%s","imageUri":"%s"}]' $CONTAINER_NAME $REGISTRY/$ECR_REPO:$IMAGE_TAG > imagedefinitions.json

artifacts:
files:
- imagedefinitions.json
Three details make this production-friendly:
  • Tests run before the image is built. A failing test stops the pipeline, so a broken image never reaches ECR.
  • Images are tagged with the commit SHA, not  latest . You can always trace a running container back to the exact commit that produced it.
  •  imagedefinitions.json  tells the ECS deploy action which container to update and which image to use.

Stage 3: Manual approval

Add an Approval action and attach an SNS topic. Reviewers receive an email with a link to approve or reject. This is your safety net for production while your automated test coverage matures.

Stage 4: Deploy

Add an Amazon ECS deploy action, choose your cluster and service, and set the image definitions file to  imagedefinitions.json . CodePipeline registers a new task definition revision and updates the service.
Enable the ECS deployment circuit breaker with rollback on the service. If new tasks repeatedly fail to reach a healthy state, ECS stops the deployment and returns to the last working revision.

4. Choosing a deployment strategy

Rolling, blue/green and canary deployment trade-offs
  • Rolling update is the ECS default. It is simple and needs no extra capacity, which makes it a good starting point.
  • Blue/green runs the new version beside the old one and shifts traffic when it is healthy. Rollback is nearly instant. It uses AWS CodeDeploy with ECS.
  • Canary sends a small percentage of traffic to the new version first. It limits impact but needs reliable metrics and alarms to be useful.
Start with rolling updates and the circuit breaker. Move to blue/green when a failed release has a real business cost.

5. Securing the pipeline

A pipeline can change production, so treat it as production.
  • Least privilege IAM. Give CodeBuild permission only to write logs, read the source artifact, and push to the one ECR repository it needs. Give CodePipeline permission only to update the one ECS service.
  • No secrets in code. Store database passwords and API keys in AWS Secrets Manager or Systems Manager Parameter Store and inject them through the ECS task definition.
  • Scan images. Turn on ECR image scanning so known vulnerabilities are reported on every push.
  • Protect the branch. Require pull request reviews on  main  so only reviewed code can start the pipeline.
  • Encrypt artifacts. Use an AWS KMS key for the pipeline artifact bucket.

6. Observability and cost

  • Send build logs to Amazon CloudWatch Logs and set an alarm on pipeline failures using Amazon EventBridge.
  • Set an ECR lifecycle policy to expire old images, for example keeping the last 20, so storage does not grow without limit.
  • CodeBuild bills by build minute, so keep builds fast with dependency caching.
  • Check current pricing for CodePipeline, CodeBuild, ECR and Fargate on the AWS pricing pages, since rates and free tier limits can change.

7. Common problems and fixes

Symptom
Likely cause
Fix
 Cannot connect to the Docker daemon  in build
Privileged mode is off
Enable privileged mode on the CodeBuild project
 no basic auth credentials  on push
ECR login failed or role lacks permission
Check the  ecr:GetAuthorizationToken  and push permissions
Deploy stage fails with image definition error
Container name mismatch
Make  name  in  imagedefinitions.json  match the container name in the task definition
Tasks keep restarting after deploy
Failing health check
Verify the health check path, port and security group rules

Conclusion

A good CI/CD pipeline is not about tools. It is about making releases boring: predictable, tested, reviewable and reversible. With CodePipeline, CodeBuild, ECR and ECS, you get that from managed services without running any build servers yourself.
Next steps
  1. Add integration tests as a second CodeBuild action.
  1. Create separate pipelines or stages for staging and production.
  1. Define the whole pipeline as code with AWS CloudFormation or AWS CDK so it is itself version controlled.
If you build this, share your results and questions in the comments. I would like to hear which deployment strategy works best for your team.

References

  • AWS CodePipeline User Guide
  • AWS CodeBuild User Guide, Build specification reference
  • Amazon ECS Developer Guide, Deployment circuit breaker
  • Amazon ECR User Guide, Lifecycle policies







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