How to Add Container Security Scanning to GitHub Actions for Go Microservices

Step‑by‑step guide to integrate container security scanning into GitHub Actions pipelines for Go microservices, covering setup, reporting, and best practices.

How to Add Container Security Scanning to GitHub Actions for Go Microservices - Cybersecurity
Short answer: Add Trivy (or another scanner) as a step in your GitHub Actions workflow, run it against the image built from your Go microservice, fail the job on vulnerabilities above your policy threshold, and publish the SARIF report to GitHub code scanning. The setup requires only a few YAML lines, a Dockerfile that builds a reproducible image, and optional secrets for private registries.

Introduction

Container security scanning is the process of automatically inspecting container images for known vulnerabilities, misconfigurations, and secret leaks before they reach production. When a Go microservice is built and packaged as a Docker image, integrating a scanner into the CI pipeline catches issues early, reduces the attack surface, and satisfies compliance requirements such as PCI‑DSS or ISO 27001.

This guide shows you how to configure Trivy in a GitHub Actions workflow that builds a Go binary, creates a Docker image, scans it, and uploads the results to GitHub’s code‑scanning UI. You will also see how to handle private registries, enforce a vulnerability‑severity policy, and generate a compliance‑ready SARIF report.

What You’ll Learn

  • Preparing a minimal Go Dockerfile that works with Trivy.
  • Setting up GitHub Actions secrets for registry credentials and SSL certificates.
  • Running Trivy (and an optional alternative) in a workflow step.
  • Failing the pipeline on high‑severity findings and publishing SARIF.
  • Common errors such as “image not found” or “unsupported OS” and how to fix them.

Prerequisites

  • A GitHub repository containing a Go module (go.mod) and a main.go entry point.
  • Docker Engine 20.10+ installed locally for testing (optional but recommended).
  • Access to a container registry (Docker Hub, GitHub Packages, or a private registry). For private registries you will need a username/password or a read‑only token.
  • GitHub Actions enabled for the repository.

Dockerfile for Go Microservices

Use a multi‑stage build to keep the final image small and free of build‑time tooling that Trivy would otherwise flag as unnecessary.

# syntax=<PLACEHOLDER>docker/dockerfile:1.4
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o microservice .

FROM alpine:3.20
# Install CA certificates for HTTPS outbound calls
RUN apk add --no-cache ca-certificates
COPY --from=builder /app/microservice /usr/local/bin/microservice
EXPOSE 8080
ENTRYPOINT ["/usr/local/bin/microservice"]

Key points:

  • Alpine 3.20 is the latest stable Alpine base as of November 2026 (Alpine releases).
  • The ca-certificates package enables SSL certificate verification for outbound calls, supporting the ssl certificate automation requirement.
  • Static linking (CGO_ENABLED=0) removes glibc dependencies, which reduces the attack surface.

Configuring GitHub Secrets (registry, SSL, SSH hardening)

Store any credential or private key in GitHub’s encrypted Secrets store. This keeps them out of the workflow logs.

Secret namePurposeValue format
REGISTRY_URLDocker registry endpoint (e.g., ghcr.io)https://ghcr.io
REGISTRY_USERUsername for private registryGitHub Actions user or robot account
REGISTRY_TOKENPersonal access token with write:packages scopeghp_********
SSL_CERTBase64‑encoded PEM for internal CA (if needed)$(cat ca.pem | base64)
SSH_PRIVATE_KEYKey used by the microservice to pull other services-----BEGIN OPENSSH PRIVATE KEY-----…
Pro Tip: Enable secret scanning in the repository settings to detect accidental commits of raw secrets.

GitHub Actions Workflow

Save the following as .github/workflows/container-scan.yml. The workflow runs on every push to main and on pull‑request events.

<!-- .github/workflows/container-scan.yml -->
name: CI – Build & Scan Go Container

on:
  push:
    branches: [main]
  pull_request:
    types: [opened, synchronize, reopened]

env:
  IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/go-microservice:${{ github.sha }}

jobs:
  build-and-scan:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      security-events: write   # required for SARIF upload

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Go
        uses: actions/setup-go@v5
        with:
          go-version: '1.22'

      - name: Build Docker image
        run: |
          docker build -t ${{ env.IMAGE_NAME }} .
          echo ${{ secrets.REGISTRY_TOKEN }} | docker login ${{ secrets.REGISTRY_URL }} -u ${{ secrets.REGISTRY_USER }} --password-stdin

      - name: Push image to registry
        run: docker push ${{ env.IMAGE_NAME }}

      - name: Install Trivy
        uses: aquasecurity/trivy-action@0.11
        with:
          # Pull the latest stable Trivy (v0.46 at time of writing)
          version: 'latest'

      - name: Scan image with Trivy
        id: trivy-scan
        run: |
          trivy image --severity HIGH,CRITICAL \
            --ignore-unfixed \
            --format sarif \
            -o trivy-report.sarif \
            ${{ env.IMAGE_NAME }}

      - name: Upload SARIF report
        uses: github/codeql-action/upload-sarif@v2
        with:
          sarif_file: trivy-report.sarif
          category: container-security-scanning

      - name: Fail on high severity findings
        if: steps.trivy-scan.outcome == 'success'
        run: |
          if grep -q 'severity="HIGH"' trivy-report.sarif || grep -q 'severity="CRITICAL"' trivy-report.sarif; then
            echo "❌ High or critical vulnerabilities detected."
            exit 1
          fi

Explanation of key steps:

  • Build Docker image – uses the Dockerfile from the repository. The image tag includes the commit SHA to guarantee uniqueness.
  • Push image – required because Trivy scans the image by digest; pushing also validates registry credentials.
  • Install Trivy – the official GitHub Action downloads the binary and adds it to PATH.
  • Scan image – --severity HIGH,CRITICAL limits the output to policy‑relevant findings; --ignore-unfixed skips vulnerabilities without a fix, which is useful for fast‑moving base images.
  • Upload SARIF – integrates results with GitHub’s code‑scanning UI, enabling “security alerts” and compliance export.
  • Fail on findings – a simple grep on the SARIF file; you can replace this with a custom policy file using --policy if you need more granularity.

Scanner Alternatives & Comparison

If Trivy does not meet a specific need (e.g., licensing, deep SBOM analysis), consider the following open‑source options.

Tool Primary Use‑Case Learning Curve Pricing Model Limits / Notable Constraints
Trivy All‑in‑one vulnerability + misconfiguration scanner; fast CLI, GitHub Action support. Low – simple commands, default DB updates. Free (Apache‑2.0). Enterprise offering adds policy‑as‑code & reporting (pricing page). DB update size ~400 MB; needs network access on first run.
Grype Vulnerability scanning with detailed CVE metadata; integrates with Syft for SBOM generation. Medium – requires separate SBOM step for full power. Free (Apache‑2.0). No commercial tier. No built‑in misconfiguration checks; relies on external policy tools.
Clair Server‑side scanner for large registries; suitable for continuous scanning of many images. High – needs deployment of a service and database. Free (Apache‑2.0). Commercial support via Red Hat Quay. Requires persistent storage; not ideal for per‑PR scans.

Common Errors & Fixes

Image not found after push

Cause: The docker login step used the wrong registry URL or token scope.

Fix: Verify that REGISTRY_URL matches the registry host (e.g., ghcr.io) and that the token includes the write:packages scope (GitHub docs).

Trivy fails with “unsupported OS”

Cause: The base image uses an OS version not present in Trivy’s vulnerability database.

Fix: Run trivy image --download-db-only in a separate step to refresh the DB, or pin the base image to a supported tag (e.g., alpine:3.20).

SARIF upload returns “no findings” but the job still fails

Cause: The grep‑based failure step looks for the literal string “severity="HIGH"” which may not appear if the SARIF format changes.

Fix: Use Trivy’s --exit-code flag instead:

trivy image --severity HIGH,CRITICAL --exit-code 1 --format sarif -o trivy-report.sarif ${{ env.IMAGE_NAME }}
The step will automatically set a non‑zero exit code.

Secrets appear in logs

Cause: Using echo ${{ secrets.REGISTRY_TOKEN }} without the --password-stdin flag prints the token.

Fix: Always pipe the secret to docker login as shown in the workflow example; GitHub masks the secret when it is passed via stdin.

Compliance Reporting

GitHub’s code‑scanning UI can be exported as a CSV for audit purposes. For frameworks that require a signed report, combine the SARIF file with a CI‑generated GPG signature.

# Generate a detached GPG signature (requires GPG secret in GitHub Secrets)
gpg --batch --yes --pinentry-mode loopback \
    --passphrase "${{ secrets.GPG_PASSPHRASE }}" \
    --output trivy-report.sarif.sig \
    --detach-sig trivy-report.sarif

Store the signature as an artifact (actions/upload-artifact) so auditors can verify integrity later.

Frequently Asked Questions

Can Trivy scan images stored in a private registry without pushing them?

Yes. Use the docker load command to load the image into the runner’s Docker daemon and then run trivy image on the local image name. Authentication still needs to be performed before docker pull.

How often does Trivy’s vulnerability database update?

Trivy updates its DB daily from the NVD, Red Hat, and Alpine security trackers. The trivy image command automatically checks for updates unless --skip-db-update is set (official docs).

Is it possible to scan for exposed secrets in the image layers?

Trivy includes a secret‑detection module that looks for high‑entropy strings. Enable it with --secret-scan. For more thorough checks, consider Gitleaks as a separate step.

Do I need to install Docker on the GitHub runner?

The ubuntu-latest runner comes with Docker pre‑installed. If you use a self‑hosted runner, ensure Docker Engine 20.10+ is available.

Can I enforce a “no critical vulnerabilities” policy across all repositories?

Yes. Create an organization‑level policy using GitHub’s code‑scanning policy that marks any SARIF result with severity “CRITICAL” as a required check failure.

How does this approach interact with SSL certificate automation?

The Dockerfile installs ca-certificates, allowing the Go binary to verify TLS connections using certificates managed by tools like cert‑manager. If your microservice needs a client certificate, inject it at runtime via a Kubernetes secret mounted as a file; the secret is not part of the image, so Trivy will not flag it.

Is SSH hardening covered by container scanning?

Trivy’s misconfiguration scanner checks for insecure SSH server settings if the image contains an sshd binary. For Go services that use SSH client libraries, hardening is performed at the application level, not the container level.

Conclusion & Next Steps

With the workflow above, every push of your Go microservice is automatically validated against the latest vulnerability database, and any high‑severity findings block the release pipeline. To extend the pipeline:

  • Integrate Trivy policy‑as‑code to enforce custom rules (e.g., disallowing root user).
  • Add a separate step that runs Gitleaks for source‑code secret detection.
  • Configure a scheduled workflow that re‑scans images older than 30 days to catch newly disclosed CVEs.
  • Export SARIF reports to a compliance dashboard (e.g., Splunk, Elastic) using the upload-artifact action.

By embedding container security scanning directly into GitHub Actions, you keep security feedback fast, reproducible, and visible to every developer on the team.

Official documentation