Gated CI image publishing

You can use service containers to test against MySQL and Redis, then gate GHCR publishing on passing checks so the next exercise can deploy identified images.

Learning outcomes

  • Configure GitHub Actions to run backend checks against disposable MySQL and Redis service containers.
  • Use healthchecks and mapped ports to make integration tests wait for ready dependencies.
  • Run linting, govulncheck, database migrations, and race-enabled Go tests in CI.
  • Publish the API and worker images to GHCR only after successful tests on the main branch.
  • Use commit SHA tags and GitHub's built-in token to identify and authenticate published images.

The API and worker now have separate production Dockerfiles. You can build both images locally, but a production deployment needs a repeatable process that verifies the source before publishing them. You need a GitHub Actions workflow that tests against MySQL and Redis, runs the required quality checks, and publishes both images only when the checks succeed on main.

Continuous integration

GitHub Actions automates repository tasks in response to events such as pushes and pull requests.

A workflow can check out your Go backend, provision its dependencies, run tests, and publish container images. This removes the dependency on a developer's local environment.

Consider a developer who has already applied every database migration locally. Their tests pass because their database is in the expected state. Another developer checks out the same commit with a fresh database and discovers that the application fails.

The source code is identical. The difference is the environment in which it was tested.

CI addresses this problem by running the checks in a clean environment.

For the food-delivery backend, your workflow needs to verify two Go binaries:

  • backend/cmd/api serves HTTP requests and runs the outbox relay.
  • backend/cmd/worker runs the notifier that consumes order events.

Both depend on MySQL and Redis. The worker also communicates with Redpanda in the deployed environment.

A successful CI run establishes that the tested revision passes the checks configured in the workflow. It does not prove that the application has no bugs, but it prevents known verification failures from being ignored during publication.

Workflow structure

A GitHub Actions workflow is a YAML file stored under .github/workflows/.

For this project, the workflow lives at:

.github/workflows/backend.yml

A workflow consists of triggers, jobs, and steps.

  • Triggers define repository events that start the workflow.
  • Jobs define independent units of work executed by runners.
  • Steps perform individual operations within a job.
  • Dependencies control which jobs must finish successfully before others start.
  • Conditions determine whether a job or step should execute.

Push and pull request triggers

Your workflow needs to run when code is pushed and when a pull request is opened or updated.

yaml
on:
  push:
  pull_request:

Both events start the test job.

A pull request should receive the same backend verification as a push. This allows contributors to discover failures before merging their changes.

Image publication has a different requirement. A pull request should not automatically publish production images.

For this project, publishing is restricted to pushes on main.

The following expression identifies that combination:

yaml
if: github.event_name == 'push' && github.ref == 'refs/heads/main'

The event condition prevents pull requests from publishing images. The branch condition prevents pushes to other branches from publishing them.

You will also use a job dependency to ensure that publishing starts only after the tests succeed.

Service containers

A GitHub-hosted runner starts with a clean environment. It does not automatically provide the MySQL and Redis instances required by your integration tests.

A service container is a container that GitHub Actions starts alongside a job. The job can connect to it while its steps execute.

Your backend test job needs two services:

ServiceImagePort
MySQLmysql:8.43306
Redisredis:76379

The workflow declares them under the test job's services property.

yaml
services:
  mysql:
    image: mysql:8.4
    env:
      MYSQL_ROOT_PASSWORD: dev
      MYSQL_DATABASE: zomato
    ports:
      - 3306:3306

  redis:
    image: redis:7
    ports:
      - 6379:6379

The MySQL service creates the zomato database and configures its root password. Redis runs without additional authentication in this disposable test environment.

These containers exist for the lifetime of the job. They are not permanent infrastructure.

Service healthchecks

A running container is not necessarily a ready service.

MySQL needs time to initialize its data directory and begin accepting database connections. If your tests start too early, they can fail even though MySQL would become available a few seconds later.

Docker healthchecks solve this startup problem.

For example:

yaml
options: >-
  --health-cmd="mysqladmin ping -h 127.0.0.1 -uroot -pdev"
  --health-interval=10s
  --health-timeout=5s
  --health-retries=10

Each option has a specific purpose:

  • --health-cmd specifies the command that checks the service.
  • --health-interval controls how frequently Docker runs the check.
  • --health-timeout limits the duration of each check.
  • --health-retries specifies how many consecutive failures are allowed.

Redis needs its own healthcheck:

yaml
options: >-
  --health-cmd="redis-cli ping"
  --health-interval=10s
  --health-timeout=5s
  --health-retries=10

redis-cli ping checks whether Redis responds successfully.

GitHub Actions waits for the configured service containers to become healthy before executing the job steps.

Port mappings

The ports property makes a container port accessible from the job runner.

For example:

yaml
ports:
  - 6379:6379

The first number is the runner's port. The second is the port inside the Redis container.

Because your tests execute directly on the GitHub-hosted runner, they connect to the mapped services through 127.0.0.1.

The Redis address is:

127.0.0.1:6379

Configure the test environment accordingly:

yaml
env:
  TEST_REDIS_ADDR: 127.0.0.1:6379
  TEST_MYSQL_DSN: root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true

The MySQL DSN describes the database connection. It contains the username, password, network address, database name, and connection options.

Notice the difference between these addresses:

  • localhost inside the Redis container refers to Redis itself.
  • localhost inside the API container refers to the API itself.
  • 127.0.0.1 in the GitHub-hosted runner refers to the runner's network interface.

Using the mapped port is what allows the runner to reach the service container.

The test job

Your test job should reproduce the backend checks that matter before publication.

These checks include dependency setup, migrations, linting, vulnerability scanning, and Go tests.

Go setup

The workflow first checks out the repository and installs the Go version used by the backend.

The actions should reference version tags rather than floating branch names.

For example:

yaml
- name: Checkout
  uses: actions/checkout@v5

- name: Set up Go
  uses: actions/setup-go@v6
  with:
    go-version: "1.27"
    cache-dependency-path: backend/go.sum

actions/checkout makes the repository files available to the runner.

actions/setup-go installs the required Go version. Its dependency cache can reuse downloaded modules when the dependency files have not changed.

Linting

Compilation and tests do not catch every code-quality problem.

The backend uses golangci-lint to run static checks against the Go code.

For example:

yaml
- name: Install golangci-lint
  uses: golangci/golangci-lint-action@v8
  with:
    version: latest
    working-directory: backend

The action runs the linter in the backend module.

You can also invoke the repository's make lint target when appropriate.

Linting catches problems before they reach the image publishing stage.

Vulnerability scanning

Your Week 6 CI workflow already contains a govulncheck step.

Keep that step when updating .github/workflows/backend.yml.

govulncheck checks Go code and its dependencies against known vulnerability information. It helps identify vulnerable functions and dependency usage that ordinary compilation and tests might not reveal.

The new image publishing workflow extends the existing CI pipeline. It does not replace the security checks already established in Week 6.

The Week 6 workflow test also verifies that govulncheck remains present. Removing it while reorganizing the jobs would break an existing requirement.

The test job should therefore retain the existing vulnerability scanning step alongside the new linting, migration, and race-testing steps.

Database migrations

The MySQL service starts with a fresh database. Your application tests need the schema created by the existing migrations.

The repository already contains its migrations under:

backend/db/migrations/

The workflow can install golang-migrate and execute the migrations before running the tests.

For example:

bash
migrate \
  -path db/migrations \
  -database "$TEST_MYSQL_DSN" \
  up

Run this command with backend as the working directory.

The up command applies all pending migrations in order. This prepares the database schema expected by the integration tests.

The order matters. Running the tests before migrations can cause missing-table or missing-column errors.

Race-enabled Go tests

Your backend uses concurrency in several places.

The WebSocket hub manages concurrent connections. Background workers process events, and shared in-memory state needs synchronization.

A data race occurs when multiple goroutines access the same memory location concurrently, at least one access is a write, and the accesses are not properly synchronized.

Go provides the race detector to identify these problems during execution.

Run the tests with:

bash
go test -race -tags redis ./...

The flags have different responsibilities:

  • -race enables race detection.
  • -tags redis includes the Redis integration tests.
  • ./... runs tests across all packages in the backend module.

The Redis build tag matters because tests using Redis-backed functionality must be included in CI.

Integration tests verify that multiple components work together. For example, a test that uses a real Redis service to exercise cache behaviour verifies more than an isolated function.

The test job should run the command from the backend directory so Go resolves the correct module and packages.

When a test fails, GitHub Actions marks the job as failed. This result must prevent image publication.

Container registry

After the backend passes its checks, you need to make its Docker images available to the deployment environment.

A container registry stores and distributes container images. It is similar to a package registry, but it stores image manifests and filesystem layers.

This project uses GitHub Container Registry (GHCR).

The API and worker images have separate repository names:

ghcr.io/yashdagar/zomato-api
ghcr.io/yashdagar/zomato-worker

The API image is built from:

backend/Dockerfile.api

The worker image is built from:

backend/Dockerfile.worker

Both builds use backend as their build context.

The build context determines which files Docker can access while building an image. Keeping it at the backend directory makes the Go module manifests and application source available to both Dockerfiles.

GHCR authentication

The workflow must authenticate before pushing images to GHCR.

GitHub Actions provides a built-in token named GITHUB_TOKEN. You can use this token instead of creating and storing a personal access token.

The publishing job needs permission to read the repository and write container packages.

yaml
permissions:
  contents: read
  packages: write

The permissions should be scoped to the image publishing job rather than granting package write access to every job.

Use the Docker login action to authenticate:

yaml
- name: Log in to GHCR
  uses: docker/login-action@v3
  with:
    registry: ghcr.io
    username: ${{ github.actor }}
    password: ${{ secrets.GITHUB_TOKEN }}

The username identifies the GitHub Actions actor. The password comes from the built-in token.

The secrets.GITHUB_TOKEN expression accesses a GitHub-provided secret. You do not need to generate a personal access token and store it manually.

Environment secrets

CI workflows sometimes need credentials for deployment, external services, or protected infrastructure.

Never commit those credentials to Git or place them inside Dockerfiles.

GitHub offers repository secrets and environment secrets.

  • Repository secrets are available to eligible workflows in a repository.
  • Environment secrets are associated with a GitHub environment, such as staging or production.

Environment secrets are useful when deployment credentials should only be available to a particular environment.

For example, a deployment job can declare:

yaml
environment: production

A protected environment can require approval before the deployment job starts. It can also restrict the branches that are allowed to deploy.

The workflow receives the environment's configured secrets after the applicable protection rules are satisfied.

For the current GHCR publishing job, the built-in GITHUB_TOKEN is sufficient. You do not need production deployment credentials merely to build and push the API and worker images.

Your MySQL test password is also different from a production password. The dev password belongs to a disposable CI service container. It is a local test configuration value, not a real account credential.

Image SHA tags

A container image can have multiple tags.

For example:

zomato-api:latest
zomato-api:v1.0.0
zomato-api:abc123

A tag provides a reference to a particular image.

However, tags such as latest can move when another image is published.

Suppose a deployment currently uses:

ghcr.io/yashdagar/zomato-api:latest

A new image is published under the same tag. The reference now points to the newer image, making it difficult to identify which source revision was originally deployed.

A commit SHA image tag identifies an image using the Git commit that produced it.

GitHub Actions exposes the commit SHA through:

yaml
${{ github.sha }}

The resulting API image reference looks like:

ghcr.io/yashdagar/zomato-api:${{ github.sha }}

The worker uses the same SHA:

ghcr.io/yashdagar/zomato-worker:${{ github.sha }}

Both images are therefore associated with the same source revision.

SHA tags provide useful release properties:

  • Traceability: You can identify the source revision associated with an image.
  • Rollback: You can retrieve the image used by a previous successful deployment.
  • Consistency: The API and worker can be deployed from the same tested commit.

A SHA tag is still technically a mutable registry reference. Someone with sufficient permissions could overwrite it. Treating commit SHA tags as immutable is a release-management convention.

For this exercise, publish only the SHA tags. Do not add latest.

Docker image builds

Docker Buildx provides the builder used by the publishing workflow.

The setup action prepares Buildx:

yaml
- name: Set up Docker Buildx
  uses: docker/setup-buildx-action@v3

The docker/build-push-action action then builds and pushes each image.

A small illustrative API build configuration looks like this:

yaml
- name: Build and push API
  uses: docker/build-push-action@v6
  with:
    context: backend
    file: backend/Dockerfile.api
    push: true
    tags: ghcr.io/yashdagar/zomato-api:${{ github.sha }}

The worker uses the same action with backend/Dockerfile.worker and the worker image name.

Notice that push: true instructs the action to publish the image to the configured registry.

Build caching

Building a Go image requires downloading modules and compiling the source.

Repeating all those operations for every commit increases CI time.

Docker supports build caching so the builder can reuse previously generated layers when their inputs remain valid.

GitHub Actions provides a cache backend through:

yaml
cache-from: type=gha
cache-to: type=gha,mode=max

cache-from attempts to reuse existing cached layers.

cache-to exports reusable layers from the current build.

The gha backend uses GitHub Actions cache storage. The mode=max setting includes intermediate build stages, which can improve caching in multi-stage Dockerfiles.

Caching improves build speed, but it does not change the correctness requirements. Docker still needs to rebuild layers whose inputs have changed.

Both API and worker builds should configure caching independently.

Test-gated image publication

The test job and image publishing job have different responsibilities.

The test job establishes whether a revision passes the required checks. The image job creates deployable artifacts from a revision that has passed those checks.

GitHub Actions supports job dependencies through needs.

For example:

yaml
jobs:
  test:
    runs-on: ubuntu-latest

  images:
    needs: test
    runs-on: ubuntu-latest

The images job waits for test to succeed.

If the test job fails, GitHub Actions skips its dependent image job by default.

This establishes a test-gated build. A failed verification stage cannot proceed to the normal image publishing stage.

A common mistake is to define test and build jobs independently without needs. GitHub Actions can run independent jobs concurrently, allowing an image to be published before tests finish.

The dependency prevents that race between verification and publication.

Main branch restriction

You also need to restrict publication to pushes on main.

The condition is:

yaml
if: github.event_name == 'push' && github.ref == 'refs/heads/main'

This prevents pull requests from publishing images.

It also prevents a push to another branch from publishing images.

The combination of needs and if gives you two separate safeguards:

  • needs enforces successful test completion.
  • if restricts publication to the intended branch and event.

This allows every pull request to run backend verification without receiving unnecessary image publishing permissions.

Action version pinning

GitHub Actions workflows depend on external actions.

For example:

yaml
uses: actions/checkout@v5

The @v5 reference selects a version tag.

Avoid floating branch references such as:

yaml
uses: actions/checkout@main

A branch can change over time. A workflow that uses a floating reference may execute different action code without any change to your repository.

Pin every action to a version tag, including checkout, Go setup, Docker Buildx setup, registry login, and Docker image builds.

For higher supply-chain assurance, production organizations may also pin actions to full commit SHAs. The contract for this exercise requires version tags.

Workflow failure investigation

A failed workflow should help you locate the problem rather than leave you guessing.

The GitHub CLI can inspect workflow runs.

Watch a running workflow:

bash
gh run watch

View logs from failed steps:

bash
gh run view --log-failed

The failed-step logs help distinguish infrastructure problems from application failures.

Check the relevant area first:

FailureWhat to investigate
MySQL service failureHealthcheck command and service startup
Redis connection failurePort mapping and TEST_REDIS_ADDR
Database query failureMySQL DSN and migration status
Linter failureStatic analysis output
Race test failureConcurrent access and synchronization
Vulnerability check failureVulnerable dependencies or code paths
Docker build failureBuild context and Dockerfile path
GHCR authentication failureToken availability and package permissions
Image publication failureImage tag and build action configuration

A failure in the test job should prevent the image job from running.

A successful image build does not guarantee that the deployed application will work correctly. It means the image was built and published after the configured verification passed.

Registry verification

After a successful workflow run, you can inspect the published package tags using GitHub CLI.

For the API:

bash
gh api users/yashdagar/packages/container/zomato-api/versions \
  --jq '.[].metadata.container.tags[]'

For the worker:

bash
gh api users/yashdagar/packages/container/zomato-worker/versions \
  --jq '.[].metadata.container.tags[]'

Look for the full commit SHA associated with the successful workflow run.

You can also retrieve an image using that tag:

bash
docker pull ghcr.io/yashdagar/zomato-api:YOUR_COMMIT_SHA

Replace YOUR_COMMIT_SHA with the actual commit identifier.

A successful pull confirms that the image is available under that registry reference. It does not replace the automated backend tests.

CI pipeline design

The pipeline has two distinct stages of responsibility.

The test job runs for pushes and pull requests. It provisions MySQL and Redis, installs the required Go tools, keeps the existing govulncheck step, applies migrations, runs linting, and executes race-enabled integration tests.

The image job runs only after the test job succeeds and only for pushes to main. It authenticates to GHCR, builds both application images, and publishes them with the same commit SHA.

The next exercise, Backend CI workflow, puts these ideas into .github/workflows/backend.yml.

Pay particular attention to the existing workflow when you make changes. The Week 6 govulncheck step is part of the established security checks and must remain. The new pipeline adds image publication without removing that earlier check.

Keep the responsibilities separate:

  • The test job verifies the backend.
  • The image job publishes deployable artifacts.
  • The SHA tags identify the source revision.
  • The GitHub token provides registry authentication.

The workflow tests inspect the YAML configuration locally. You do not need to push an actual image to complete the exercise.

Check your understanding

Question 1 of 4

Your MySQL and Redis service containers are running, but tests fail intermittently because MySQL is still initializing. What should you change?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (GitHub Actions, Docker).

Finished Lesson 7.3?