Skip to content
notes.vinhnq.com

Search

Git, DevOps & ToolingMid19 min read

CI/CD for a Spring Boot backend: a GitHub Actions pipeline from commit to production

Review 15 cards
On this page

The CI/CD pipeline is the only road from commit to production; if it’s slow, under-tested or leaks secrets, the whole team pays. This post builds a complete GitHub Actions workflow for a Spring Boot service and explains each decision: where tests run, how images are tagged, when migrations run, and how to roll back. Read Docker for Spring Boot and the 12-Factor App first.

1. CI, continuous delivery and continuous deployment

Key idea: three concepts in sequence. CI answers “does this code break anything”, continuous delivery answers “is this build ready to release”, continuous deployment removes the human click altogether.

Continuous integration Continuous delivery Continuous deployment
Automated up to build + test on every commit, frequent merges to trunk staging; production waits for approval production
Requires trustworthy automated tests repeatable deploys, a production-like environment excellent tests, monitoring, automatic rollback; feature flags
Fits every team most backend teams web products deploying many times a day

Measure “a good pipeline” with the four DORA metrics: deployment frequency, lead time from commit to production, change failure rate, time to restore.

2. The shape of a pipeline

Key idea: a PR only builds and tests; a merge to main adds the image build and a staging deploy; a v1.4.0 tag promotes that same image to production. Cheap, failure-prone steps come first for early feedback.

flowchart LR
  PR[Pull request] --> BT["build-test: compile, unit, Testcontainers, static analysis"]
  M[Push main] --> BT --> IMG["image: build, scan, push sha-commit"] --> STG["deploy staging"]
  TAG["Tag v1.4.0"] --> PRO["promote: tag the existing digest as 1.4.0"] --> APP{"Production approval"} --> PROD["deploy production"]

“Build once” is factor V of 12-factor: what runs in production is exactly what was tested. The image built from main carries the tag sha-<commit>; the release tag only adds a 1.4.0 label to the same digest.

3. The complete workflow

Key idea: two files: ci-cd.yml orchestrates build, image and promotion; deploy.yml is a reusable workflow shared by staging and production. Both pass actionlint (with shellcheck); they weren’t run for real, since that needs a repo, a registry and a cluster.

ci-cd.yml, deploy.yml and Dockerfile.ci

.github/workflows/ci-cd.yml:

name: ci-cd

on:
  pull_request:
  push:
    branches: [main]
    tags: ['v*.*.*']

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
  contents: read

env:
  IMAGE: ghcr.io/acme/orders-service

jobs:
  build-test:
    if: github.ref_type != 'tag'
    runs-on: ubuntu-24.04
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-java@v6
        with:
          distribution: temurin
          java-version: '21'
          cache: maven
      # unit test (Surefire), Testcontainers IT (Failsafe), Checkstyle, SpotBugs, JaCoCo
      - run: ./mvnw -B -ntp verify
      - if: failure()
        uses: actions/upload-artifact@v7
        with:
          name: test-reports
          path: target/*-reports/
      - if: github.event_name == 'push'
        uses: actions/upload-artifact@v7
        with:
          name: app-jar
          path: target/*.jar
          retention-days: 7

  image:
    needs: build-test
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      packages: write
    outputs:
      digest: ${{ steps.push.outputs.digest }}
    steps:
      - uses: actions/checkout@v7
      - uses: actions/download-artifact@v8
        with:
          name: app-jar
          path: target
      - uses: docker/setup-buildx-action@v4
      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: meta
        uses: docker/metadata-action@v6
        with:
          images: ${{ env.IMAGE }}
          tags: type=sha,format=long
      - name: Build locally for scanning
        uses: docker/build-push-action@v7
        with:
          context: .
          file: Dockerfile.ci
          load: true
          tags: orders-service:scan
          cache-from: type=gha
      - name: Scan before anything is pushed
        uses: aquasecurity/trivy-action@v0.36.0
        with:
          image-ref: orders-service:scan
          severity: CRITICAL,HIGH
          ignore-unfixed: true
          exit-code: '1'
      - id: push
        uses: docker/build-push-action@v7
        with:
          context: .
          file: Dockerfile.ci
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          sbom: true

  deploy-staging:
    needs: image
    uses: ./.github/workflows/deploy.yml
    with:
      environment: staging
      image: ghcr.io/acme/orders-service@${{ needs.image.outputs.digest }}
    secrets: inherit

  promote:
    if: github.ref_type == 'tag'
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      packages: write
    outputs:
      digest: ${{ steps.resolve.outputs.digest }}
    steps:
      - uses: docker/setup-buildx-action@v4
      - uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: resolve
        name: Find the image already built and tested from this commit
        run: |
          DIGEST=$(docker buildx imagetools inspect "$IMAGE:sha-$GITHUB_SHA" \
            --format '{{json .Manifest}}' | jq -r .digest)
          docker buildx imagetools create --tag "$IMAGE:${GITHUB_REF_NAME#v}" "$IMAGE@$DIGEST"
          echo "digest=$DIGEST" >> "$GITHUB_OUTPUT"

  deploy-production:
    needs: promote
    uses: ./.github/workflows/deploy.yml
    with:
      environment: production
      image: ghcr.io/acme/orders-service@${{ needs.promote.outputs.digest }}
    secrets: inherit

.github/workflows/deploy.yml:

name: deploy

on:
  workflow_call:
    inputs:
      environment:
        type: string
        required: true
      image:
        type: string
        required: true

jobs:
  deploy:
    runs-on: ubuntu-24.04
    environment: ${{ inputs.environment }}
    concurrency:
      group: deploy-${{ inputs.environment }}
      cancel-in-progress: false
    timeout-minutes: 30
    steps:
      - uses: actions/checkout@v7
      - name: Flyway migrate (expand-only migrations)
        env:
          FLYWAY_URL: ${{ secrets.DB_URL }}
          FLYWAY_USER: ${{ secrets.DB_MIGRATION_USER }}
          FLYWAY_PASSWORD: ${{ secrets.DB_MIGRATION_PASSWORD }}
        run: |
          docker run --rm -e FLYWAY_URL -e FLYWAY_USER -e FLYWAY_PASSWORD \
            -v "$PWD/src/main/resources/db/migration:/flyway/sql:ro" \
            flyway/flyway:13 -validateMigrationNaming=true migrate
      - name: Configure kubectl
        env:
          KUBECONFIG_DATA: ${{ secrets.KUBECONFIG }}
        run: |
          mkdir -p ~/.kube
          printf '%s' "$KUBECONFIG_DATA" > ~/.kube/config
          chmod 600 ~/.kube/config
      - id: rollout
        name: Roll out
        env:
          IMAGE: ${{ inputs.image }}
        run: |
          kubectl -n orders set image deployment/orders-service app="$IMAGE"
          kubectl -n orders rollout status deployment/orders-service --timeout=5m
      - name: Smoke test
        env:
          BASE_URL: ${{ vars.BASE_URL }}
        run: curl -fsS --retry 5 --retry-all-errors "$BASE_URL/actuator/health/readiness"
      - name: Roll back on failure
        if: failure() && steps.rollout.outcome != 'skipped'
        run: kubectl -n orders rollout undo deployment/orders-service

Dockerfile.ci only packages the tested jar (the full version with a build stage is in the Docker post):

FROM eclipse-temurin:21-jre AS extract
WORKDIR /x
COPY target/*.jar app.jar
RUN java -Djarmode=tools -jar app.jar extract --layers --destination out

FROM eclipse-temurin:21-jre
RUN groupadd --system app && useradd --system --gid app --no-create-home app
WORKDIR /app
COPY --from=extract /x/out/dependencies/ ./
COPY --from=extract /x/out/spring-boot-loader/ ./
COPY --from=extract /x/out/snapshot-dependencies/ ./
COPY --from=extract /x/out/application/ ./
USER app
ENV JAVA_TOOL_OPTIONS="-XX:MaxRAMPercentage=75 -XX:+ExitOnOutOfMemoryError"
ENTRYPOINT ["java", "-jar", "app.jar"]

Assumptions: the POM binds Checkstyle, SpotBugs and JaCoCo (with a coverage threshold) to the verify phase; the Kubernetes Deployment is orders-service with a container named app; GitHub environments staging and production exist, and production has a required reviewer and only allows v* tags. I checked extract --layers with the jar renamed to app.jar (the application layer contains exactly app.jar). Action versions are the latest GitHub releases as of 18 Nov 2026.

Worth noticing:

  • permissions: contents: read for the whole workflow; only the job that pushes the image adds packages: write.
  • concurrency: a new push to a PR cancels the old run; deploys to the same environment queue up and are never cancelled midway.
  • The image is scanned before it’s pushed, so an image with serious vulnerabilities never gets a sha-<commit> tag to promote.
  • promote doesn’t build or retest; it looks up the digest by the tag’s commit. A tag on a commit that never passed the main pipeline fails, which is exactly what we want.
  • Rollback only runs if the rollout step ran.

4. Build and test: Maven cache, unit tests, Testcontainers

Key idea: one ./mvnw verify runs unit tests (Surefire) and integration tests (Failsafe). GitHub’s Ubuntu runners have Docker preinstalled, so Testcontainers works with no setup; caching ~/.m2 avoids downloading dependencies every time.

  • Surefire runs *Test in the test phase; Failsafe runs *IT in integration-test and fails the build in verify. Unit tests fail early, slow tests stay separate.
  • Testcontainers: how to write them and keep the context fast is in testing Spring Boot with Testcontainers. Flyway runs migrations against the container on every test run, so a broken migration turns CI red before it reaches staging.
  • cache: maven stores ~/.m2/repository keyed by the hash of the pom.xml files; -B -ntp keeps logs clean (no download progress).

5. Static analysis and quality gates

Key idea: a quality gate is a “no pass, no merge” rule: green tests, no new static analysis findings, enough coverage on new code, no serious vulnerabilities. Wire it into required status checks in branch protection so nobody can skip it.

Check Common tools Runs where
Formatting, bug patterns, coverage Spotless, Checkstyle, SpotBugs, Error Prone, JaCoCo verify
Overall quality SonarQube/SonarCloud quality gate on new code separate job
Dependency vulnerabilities OWASP Dependency-Check, Dependabot, Renovate daily schedule + PRs
Image vulnerabilities Trivy, Grype before pushing the image

6. Images: tags, versions and promotion across environments

Key idea: each image has an immutable per-commit tag (sha-<commit>), releases add a SemVer tag (1.4.0), and deploys always reference the digest. Promotion adds a label to an existing digest, with no rebuild.

  • Release tags follow SemVer and match the Git tag v1.4.0 (Git: tags and SemVer); never deploy latest (Docker post), and enable tag immutability in the registry if available.
  • Per-environment config lives outside the image (environment variables, Secrets, ConfigMaps): same image, different config.

7. Secrets in CI

Key idea: secrets live in GitHub Secrets (ideally environment secrets), jobs get minimal permissions, and for the cloud use OIDC: GitHub issues a short-lived token, the cloud exchanges it for temporary credentials, and there’s no long-lived key left to leak.

  • Environment secrets: production secrets are readable only by jobs with environment: production, after a reviewer approves.
  • OIDC: add permissions: id-token: write; the cloud (AWS, GCP, Azure) trusts tokens whose claims match the repo and environment. No more access keys living for years in settings.
  • GitHub masks secrets in logs, but not transformed values (base64, substrings). Don’t echo secrets.
  • Don’t pass secrets as command-line arguments (visible in the process list); the workflow above uses FLYWAY_* environment variables. Secret files like kubeconfig get chmod 600.

8. Database migrations in the pipeline (Flyway)

Key idea: migrations are checked in CI (Testcontainers runs Flyway against a real database), run in a separate step before the rollout with a DDL-capable account, and are always backward compatible so old code still runs on the new schema.

  • Backward compatible because during a rolling update, old and new pods run on the new schema together; on rollback, old code runs on the new schema. Renaming or dropping a column takes several releases (exercise 2).
  • At app startup or as a separate step: compared in 12-factor. The workflow above uses a separate step; if the database is only reachable from the internal network, use a self-hosted runner in the VPC or run Flyway as a Kubernetes Job.
  • The app account only needs data read/write; only the migration account has DDL rights.
  • Long migrations (an index on a big table): CREATE INDEX CONCURRENTLY on PostgreSQL, online DDL on MySQL (online DDL post).

9. Branching and releases

Key idea: the pipeline above suits trunk-based development: small PRs living hours to a day, a merge to main goes to staging, releases are tags. Git Flow needs extra pipelines for develop and release/*, and feedback is slower.

  • The models are compared in the branching post; here only the CI consequences.
  • Trunk-based needs feature flags: unfinished code can still merge, switched off by a flag; deploying isn’t releasing a feature.
  • Branch protection on main: PRs required, required status check build-test, at least one review.
  • Hotfix: fix on main, tag v1.4.1; if an old version must be patched, cut a release branch from its tag.

10. Deploy and rollback

Key idea: deploying means changing the digest the Deployment runs and waiting for the rollout; rolling back means running the previous digest again. The database doesn’t roll back with it, so the schema must work with both code versions.

  • Rolling, blue-green, canary and readiness probes belong to the post on deployment strategies; this workflow just calls kubectl set image and rollout status.
  • Automatic rollback when the rollout or smoke test fails (rollout undo); manual rollback by rerunning deploy.yml with the old digest, or git revert of the config commit with GitOps (Argo CD, Flux).
  • A logic bug already in production: turning off the feature flag is faster than rolling back.
  • A broken migration: write a new migration to fix it (forward fix); Flyway Community has no undo.

11. A faster pipeline

Key idea: a common target is PR feedback in about 10 minutes. Measure each step’s time first, then cut the biggest part.

  • Caching: ~/.m2 via setup-java, image layers via type=gha.
  • Fail fast: unit tests before Testcontainers; concurrency cancels stale runs.
  • Parallelism: static analysis and tests as separate jobs; Surefire forkCount.
  • Testcontainers: one container for the whole suite, keep the Spring context cached, avoid @DirtiesContext.
  • Drop waste: don’t run tests twice (Maven, then again in the Dockerfile); paths filters for docs-only changes.
  • timeout-minutes on every job so a hung job doesn’t hold a runner for hours.

Exercises

Exercise 1: Speed up a 25-minute pipeline

Task. A PR pipeline takes 25 minutes: 4 minutes downloading dependencies, 3 minutes compile and unit tests, 12 minutes integration tests (40 classes, each starting its own PostgreSQL and Kafka), 6 minutes docker build (the Dockerfile runs mvn package with tests). Propose changes and estimate the new time.

Solution to Exercise 1: the changes and the estimate

The numbers below are order-of-magnitude estimates; measure again after each change.

  1. Maven cache (setup-java cache: maven): 4 minutes of downloads become a few dozen seconds of cache restore when the POM is unchanged.
  2. Shared Testcontainers: 40 starts of PostgreSQL + Kafka become one for the whole suite (an abstract base class holding static containers, or @ServiceConnection with shared beans), and the Spring context is not recreated. Most of the 12 minutes is container and context startup, so this could drop to 3–4 minutes.
  3. No image build on PRs: the image is only needed after merging to main. PRs save the full 6 minutes. On main, the Dockerfile only copies the tested jar instead of rerunning mvn package, plus type=gha layer cache: about 1 minute.
  4. Parallelism: static analysis runs as a separate job alongside tests.
  5. Cancel stale runs: concurrency with cancel-in-progress when pushing repeatedly to a PR.

Estimated PR result: ~0.5 + 3 + 3.5 ≈ 7 minutes. Verify by comparing per-step times before and after in the Actions tab, tracking median and p90 over a few dozen runs, not a single one.

Exercise 2: Rename a column with zero downtime through the pipeline

Task. Table orders has a column customer_name that should become full_name. The service runs 3 pods, uses rolling updates, and must be able to roll back one version. Write the sequence of migrations and releases.

Solution to Exercise 2: expand, migrate, contract over three releases

With ALTER TABLE orders RENAME COLUMN in one release, old pods still running (and the old version after a rollback) fail immediately because customer_name is gone. Split it into three releases:

Release 1 (expand).

-- V12__add_full_name.sql
ALTER TABLE orders ADD COLUMN full_name varchar(200);

Code writes both columns and reads COALESCE(full_name, customer_name). Rolling back to the old version is still safe: it doesn’t know about full_name, and the new column allows NULL.

Release 2 (migrate).

-- V13__backfill_full_name.sql  (big table: run in batches outside the migration)
UPDATE orders SET full_name = customer_name WHERE full_name IS NULL;

Code reads only full_name but still writes both columns so release 1 (the rollback target) reads correctly. For a big table, backfill in batches as in deleting old data safely to avoid long locks.

Release 3 (contract), once you’re sure you won’t roll back to release 1:

-- V14__drop_customer_name.sql
ALTER TABLE orders ALTER COLUMN full_name SET NOT NULL;
ALTER TABLE orders DROP COLUMN customer_name;

Code stops writing customer_name from release 3; that’s safe because the rollback target is now release 2, which already reads only full_name. Each migration goes through the pipeline like any other change: run on Testcontainers in CI, then the Flyway step before the rollout on staging and production.

Not run: my machine has no PostgreSQL and Docker isn’t running, so the SQL was only checked by re-reading the syntax.

Remember

  • Explain how CI, continuous delivery and continuous deployment differ, and when to keep an approval button.
  • Redraw the pipeline: PR, main, tag; know which step runs where and why the image is built only once.
  • Know how to keep secrets safe: environment secrets, OIDC, minimal permissions, actions pinned by SHA.
  • Write an expand → contract migration sequence and explain why rolling back code doesn’t roll back the database.
  • Name at least five ways to make a pipeline faster, and measure before optimising.

Interview questions

Junior

How do CI, continuous delivery and continuous deployment differ?

CI builds and tests every commit automatically; continuous delivery keeps every build deployable, with production one click away; continuous deployment goes to production with no click.

CI is the foundation of the other two. The only difference between delivery and deployment is whether a person approves the last step, but deployment demands much stronger tests, monitoring and automatic rollback.

What steps should a pipeline for a Spring Boot service have?

Compile, unit tests, integration tests (Testcontainers), static analysis, image build, vulnerability scan, image push, staging deploy, smoke test, then an approved production deploy.

The order follows the rule that cheap, failure-prone steps run first for early feedback. Test results and reports are kept as artifacts to inspect when a job fails.

Mid

Why build an image once and promote it instead of building per environment?

So that what runs in production is exactly what was tested; a rebuild can produce a different image (changed dependencies or base image), and rollback loses its anchor.

The image is tagged by commit and deployed by digest; environments differ only in config injected at runtime. Promotion just adds a release tag to the existing digest.

How do you manage secrets in a pipeline?

Keep secrets in GitHub Secrets per environment, give each job minimal permissions, and use OIDC to get short-lived cloud credentials instead of storing long-lived keys.

Also: never print secrets, never pass them as command-line arguments, never run fork code with secrets (pull_request_target), pin third-party actions by SHA. Production secrets are only readable after the environment’s approval step.

How does trunk-based development affect the pipeline?

Every merge to main must be deployable, so CI must be fast and trustworthy, and unfinished features must hide behind feature flags.

In return, merge conflicts are rare and feedback is fast. Git Flow allows longer-lived branches but needs pipelines for develop and release/*, and late integration means bugs surface late.

Senior

A deploy fails after the migration has already run. How do you roll back?

Roll back the code by redeploying the previous digest; the database stays as is because the migration was written to be backward compatible. If the migration itself is wrong, fix it with a new migration.

This only holds if the team follows expand → contract: no renaming or dropping columns in the same release as the code that uses them. Flyway Community has no undo migrations, and undoing written data is almost always riskier than a forward fix. For a logic bug, turn off the feature flag first, roll back second.

A PR pipeline takes 40 minutes. How do you speed it up?

Measure each step first, then attack the biggest: cache dependencies and layers, share Testcontainers and the Spring context, parallelise, and drop work PRs don’t need.

  • Cache ~/.m2 and Docker layers (type=gha).
  • One container for the whole suite, avoid @DirtiesContext, keep the context cache.
  • No image build on PRs; don’t run tests twice.
  • Static analysis and tests in parallel; cancel stale runs with concurrency.
  • Track median and p90 pipeline time as a team metric.
How do you keep a compromised third-party action from stealing your secrets?

Pin actions to a commit SHA, restrict GITHUB_TOKEN permissions, expose secrets only to jobs that truly need them, and allow only approved actions.

The 2025 tj-actions/changed-files incident showed that tags can be moved to malicious code. Also: use OIDC so credentials expire quickly, separate deploy jobs (with secrets) from build jobs (which run lots of external code), and let Dependabot propose SHA updates for review.

Useful phrases for interviews

  • “Every merge to main goes through the same pipeline.”
  • “We build the artifact once and promote the same digest through every environment.”
  • “Promoting a release just adds a tag to an existing digest.”
  • “Cheap, failure-prone steps run first so developers get feedback early.”
  • “The quality gate only applies to new code.”
  • “OIDC gives us short-lived credentials instead of static keys.”
  • “We pin third-party actions to a full commit SHA.”
  • “Every migration must be backward compatible with the previous release.”
  • “We rename columns with expand and contract over three releases.”
  • “Rolling back means redeploying the previous digest; the schema only moves forward.”

Self-compiled notes from official documentation and hands-on practice.