Overview and What You Will Learn
A Docker CI/CD pipeline builds an image from a commit, tests and scans it, pushes it to a registry under an immutable tag, and deploys exactly that tag. Doing the steps in the right order means you never ship a known critical vulnerability, and you can always roll back to a specific earlier build.
In this lab you will:
- Write a multi-stage Dockerfile that produces a small, non-root production image.
- Build once on every pull request, and push only from the
mainbranch. - Fail the pipeline on HIGH and CRITICAL vulnerabilities with Trivy before anything is pushed.
- Authenticate to AWS ECR with short-lived OIDC credentials instead of stored keys.
- Deploy a specific image tag to an EC2 host with Compose, verify health, and roll back automatically.
Why This Matters in Production
Teams that deploy several times a day cannot rely on manual checks. A scan gate stops a vulnerable base image at the pull request, not after it reaches production, and an immutable tag per commit turns a bad release into a one-line rollback instead of an investigation. Payment-focused teams at companies like Razorpay and Stripe treat these properties as table stakes because an outage or a known vulnerability costs far more than the minutes the checks take.
The pipeline also becomes your audit trail. Each running container maps to a commit, a build log, and a scan report.
Core Principles
Order matters: test first because it is cheapest, scan before pushing so a vulnerable image never reaches the registry, and deploy only what was scanned.
Principles to follow:
- Scan the exact image you will push. Build it locally, scan it, then tag and push the same image.
- Use immutable tags. Tag by commit SHA. Avoid pushing
latest, and enable immutable tags on the ECR repository. - Never store long-lived cloud keys in CI. Use GitHub OIDC to assume an IAM role for the duration of the job.
- Deploy by tag, verify, then keep the old tag. The previous tag is your rollback.
- Run PR builds too. Building and scanning on pull requests finds problems before merge, while pushing and deploying stay limited to
main.
Detailed Step-by-Step Practical Lab
How to Write a Multi-Stage Production Dockerfile
FROM node:20-alpine AS builderWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run build FROM node:20-alpine AS productionWORKDIR /appENV NODE_ENV=productionRUN addgroup -S appgroup && adduser -S appuser -G appgroupCOPY package.json package-lock.json ./RUN npm ci --omit=dev && npm cache clean --forceCOPY --from=builder /app/dist ./distUSER appuserEXPOSE 3000HEALTHCHECK --interval=30s --timeout=5s --start-period=15s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1CMD ["node", "dist/server.js"]Add a .dockerignore that excludes node_modules, .git, and .env* so the build context stays small and free of secrets.
How to Prepare ECR and AWS Access Once
# Create the repository with immutable tags and scan-on-pushaws ecr create-repository \ --repository-name payment-api \ --image-tag-mutability IMMUTABLE \ --image-scanning-configuration scanOnPush=true \ --region ap-south-1In IAM, create an OIDC identity provider for token.actions.githubusercontent.com and a role (for example github-actions-ecr-push) whose trust policy is limited to your repository and branch. Grant it only the ECR push permissions it needs, such as ecr:GetAuthorizationToken, ecr:BatchCheckLayerAvailability, ecr:InitiateLayerUpload, ecr:UploadLayerPart, ecr:CompleteLayerUpload, and ecr:PutImage.
How to Write the GitHub Actions Workflow
# .github/workflows/ci-cd.ymlname: Docker CI/CD on: push: branches: [main] pull_request: branches: [main] permissions: contents: read id-token: write # lets the job request an OIDC token for AWS env: AWS_REGION: ap-south-1 ECR_REPOSITORY: payment-api jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: "20" cache: npm - run: npm ci - run: npm test build-scan-push: needs: test runs-on: ubuntu-latest outputs: image-tag: ${{ steps.vars.outputs.tag }} steps: - uses: actions/checkout@v4 - name: Compute image tag id: vars run: echo "tag=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT" - uses: docker/setup-buildx-action@v3 - name: Build image locally uses: docker/build-push-action@v6 with: context: . load: true push: false tags: ${{ env.ECR_REPOSITORY }}:${{ steps.vars.outputs.tag }} cache-from: type=gha cache-to: type=gha,mode=max - name: Scan image with Trivy uses: aquasecurity/trivy-action@0.28.0 # pin a release tag or commit SHA with: image-ref: ${{ env.ECR_REPOSITORY }}:${{ steps.vars.outputs.tag }} format: table severity: HIGH,CRITICAL ignore-unfixed: true exit-code: "1" - name: Configure AWS credentials (OIDC) if: github.ref == 'refs/heads/main' uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-actions-ecr-push aws-region: ${{ env.AWS_REGION }} - name: Log in to Amazon ECR if: github.ref == 'refs/heads/main' id: ecr uses: aws-actions/amazon-ecr-login@v2 - name: Tag and push if: github.ref == 'refs/heads/main' run: | LOCAL="${ECR_REPOSITORY}:${{ steps.vars.outputs.tag }}" REMOTE="${{ steps.ecr.outputs.registry }}/${LOCAL}" docker tag "$LOCAL" "$REMOTE" docker push "$REMOTE" deploy: needs: build-scan-push if: github.ref == 'refs/heads/main' runs-on: ubuntu-latest environment: production steps: - name: Deploy over SSH uses: appleboy/ssh-action@v1.2.0 # pin a release tag or commit SHA with: host: ${{ secrets.EC2_HOST }} username: ubuntu key: ${{ secrets.EC2_SSH_KEY }} script: | set -euo pipefail cd /opt/payment-api NEW_TAG="${{ needs.build-scan-push.outputs.image-tag }}" PREVIOUS_TAG=$(grep '^IMAGE_TAG=' .env | cut -d= -f2) aws ecr get-login-password --region ap-south-1 | \ docker login --username AWS --password-stdin \ 123456789012.dkr.ecr.ap-south-1.amazonaws.com sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=${NEW_TAG}/" .env docker compose pull payment-api if ! docker compose up -d --no-deps --wait --wait-timeout 90 payment-api; then echo "Deploy of ${NEW_TAG} failed, rolling back to ${PREVIOUS_TAG}" sed -i "s/^IMAGE_TAG=.*/IMAGE_TAG=${PREVIOUS_TAG}/" .env docker compose up -d --no-deps --wait payment-api exit 1 fiHow to Configure the Deploy Host
The host keeps a compose.yaml that references the tag from .env, and an instance role that can pull from ECR.
# /opt/payment-api/compose.yamlservices: payment-api: image: 123456789012.dkr.ecr.ap-south-1.amazonaws.com/payment-api:${IMAGE_TAG} restart: unless-stopped ports: - "127.0.0.1:3000:3000" healthcheck: test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/health"] interval: 15s timeout: 5s retries: 3 start_period: 15s# /opt/payment-api/.envIMAGE_TAG=9b21d4eGrant the instance role only ecr:GetAuthorizationToken, ecr:BatchGetImage, and ecr:GetDownloadUrlForLayer.
How to Run the Trivy Scan Locally
docker build -t payment-api:local . trivy image \ --severity HIGH,CRITICAL \ --ignore-unfixed \ --exit-code 1 \ payment-api:local # Machine-readable output for dashboards or the GitHub Security tabtrivy image --format sarif -o trivy-results.sarif payment-api:localHow to Roll Back by Hand
cd /opt/payment-apised -i 's/^IMAGE_TAG=.*/IMAGE_TAG=9b21d4e/' .envdocker compose pull payment-apidocker compose up -d --no-deps --wait payment-apidocker inspect payment-api-payment-api-1 --format '{{.Config.Image}}'Production Best Practices & Common Pitfalls
- Tag by commit SHA and keep tags immutable: every deployed container maps to one commit, and rollback is exact.
- Treat the scan as a hard gate:
exit-code: "1"on HIGH and CRITICAL stops the release. Useignore-unfixedto avoid blocking on issues with no available fix, and track those separately. - Pin third-party actions: use release tags or commit SHAs rather than
@master, because a moved branch can change your pipeline without a pull request. - Use OIDC, not stored access keys: short-lived credentials limit the damage of a leaked token.
- Protect production with an environment: a GitHub
environmentcan require approval before the deploy job runs. - Be honest about downtime: recreating a container on one host causes a brief interruption. For zero-downtime releases you need multiple instances behind a load balancer or an orchestrator.
- Build on pull requests: catching a failing build or a vulnerable dependency before merge is cheaper than catching it on
main.
TipAdd a lifecycle policy to the ECR repository that expires old untagged images and keeps the last 20 to 30 tagged ones, so storage costs stay bounded while rollbacks remain possible.
RememberScan the local image before pushing. If you push first and scan afterwards, a vulnerable image already sits in the registry and may be pulled by other jobs.
Common MistakePushing only
latest, or pushinglatestto a repository with immutable tags. The first makes rollback impossible, and the second fails on the second push. Use the commit SHA tag.
SecurityLimit the OIDC role's trust policy to your repository and branch, and give the CI role push-only ECR access. Never attach
AdministratorAccessto a CI role or a production instance profile.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker build -t app:$(git rev-parse --short HEAD) . |
Build with a commit tag |
trivy image --severity HIGH,CRITICAL <image> |
Scan an image |
aws ecr get-login-password --region ap-south-1 |
Get a short-lived ECR password |
docker compose up -d --no-deps --wait <svc> |
Recreate one service and wait for health |
docker inspect <ctr> --format '{{.Config.Image}}' |
Confirm the running image tag |
aws ecr describe-images --repository-name payment-api |
List pushed tags |
| Problem | Likely cause | Fix |
|---|---|---|
tag invalid: already exists |
Immutable tags and a repeated tag | Use a unique SHA tag |
| Trivy fails the build | HIGH or CRITICAL CVE in base or deps | Update the base image or dependency |
Not authorized to perform sts:AssumeRoleWithWebIdentity |
Trust policy mismatch | Check repo, branch, and id-token: write |
| Deploy step hangs | Health check never passes | Check docker compose logs on the host |
| Wrong version running | .env tag not updated |
Verify with docker inspect and fix the tag |