Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 44 ยท GitHub Actions in Practice

CI for Java, Go and PHP Projects

Build and test Java, Go and PHP projects in GitHub Actions: setup actions, dependency caching, test reports and a database service container for integration tests.

In the previous lesson you built a pipeline for two interpreted languages. Java, Go and PHP follow the same skeleton: check out the code, install a toolchain, restore a dependency cache, build, test and publish the results. What changes is the toolchain action, the cache location and the shape of the test output. There is one more new piece too. Real back-end projects almost always need a database during tests, and GitHub Actions can start one for you as a service container.

In this lesson you will write a workflow for each of the three languages, learn how the built-in caches work, see how to surface test reports, and wire up a PostgreSQL service with a health check. None of the real workflows can run on this site (there is no GitHub runner here), so the YAML is read-only. The runnable examples are small stand-ins that show the ideas that matter: how a cache key is built from a lock file, and how a job waits for a service container to become healthy.

The common skeleton

Every compiled or dependency-heavy project needs the same five moves. Keeping them in the same order in all your repositories makes workflows easy to read and review.

flowchart LR
    A["checkout"] --> B["setup toolchain<br/>(java / go / php)"]
    B --> C["restore dependency cache"]
    C --> D["build + test"]
    D --> E["upload reports<br/>and artifacts"]

The same five steps apply to every language; only the setup action and cache paths change.

Each language has an official setup-* action published by GitHub. They install a specific version of the toolchain on the runner (the runner image already ships with several versions, but pinning a version in the workflow makes your build reproducible). Most of them can also cache your dependencies if you ask, which saves you from writing a separate actions/cache step. If you need a refresher on cache keys, see Caching and Artifacts.

Java with Maven or Gradle

actions/setup-java needs two inputs: a distribution (which vendor's JDK) and a version. Temurin, the Eclipse Adoptium build, is a common neutral choice. Setting cache: maven or cache: gradle makes the action restore and save the local repository (~/.m2/repository or ~/.gradle), with a key derived from your pom.xml or Gradle files.

YAML
name: Java CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        java: [17, 21]
    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK ${{ matrix.java }}
        uses: actions/setup-java@v4
        with:
          distribution: temurin
          java-version: ${{ matrix.java }}
          cache: maven

      - name: Build and test
        run: mvn --batch-mode --no-transfer-progress verify

      - name: Upload test reports
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: surefire-reports-java-${{ matrix.java }}
          path: target/surefire-reports/

A few details are worth noticing:

  • --batch-mode turns off Maven's interactive colors and progress bars, and --no-transfer-progress stops the log from filling with download lines. Logs become shorter and easier to search.
  • mvn verify runs the build, the unit tests and any integration tests bound to the later phases. For a Gradle project the equivalent is ./gradlew build; use the Gradle wrapper (gradlew) so every machine uses the same Gradle version.
  • The artifact step has if: always(). Without it, the step would be skipped exactly when you need the reports most: after a test failure.
  • The artifact name includes the matrix value. Two matrix jobs uploading to the same name would conflict.

Go

actions/setup-go has the smallest configuration of the three. It reads the version from the go.mod file if you ask it to, and it caches the module download cache and the build cache by default, keyed on go.sum.

YAML
name: Go CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod

      - name: Check formatting
        run: test -z "$(gofmt -l .)"

      - name: Vet
        run: go vet ./...

      - name: Test with the race detector
        run: go test -race -count=1 -coverprofile=coverage.out ./...

      - name: Show coverage summary
        run: go tool cover -func=coverage.out | tail -n 1

The go-version-file: go.mod input means the version is written in one place only, in your module file. The -count=1 flag disables Go's test result cache so CI always runs the tests rather than replaying a remembered result. -race turns on the data-race detector, which is worth its slower runtime in CI. The formatting check works because gofmt -l prints the names of files that need formatting, and test -z fails if that output is not empty.

For a deeper look at the language itself, see the Go tutorial.

PHP with Composer

PHP is the odd one out: setup-php is not an official GitHub action but a widely used community action, shivammathur/setup-php. It installs PHP, extensions and tools such as Composer. It does not cache dependencies by itself, so you cache Composer's download cache with actions/cache, using the composer.lock file as the key.

YAML
name: PHP CI

on:
  push:
    branches: [main]
  pull_request:

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: shivammathur/setup-php@v2
        with:
          php-version: "8.4"
          extensions: mbstring, pdo_sqlite
          coverage: none

      - name: Find the Composer cache directory
        id: composer-cache
        run: echo "dir=$(composer config cache-files-dir)" >> "$GITHUB_OUTPUT"

      - uses: actions/cache@v4
        with:
          path: ${{ steps.composer-cache.outputs.dir }}
          key: composer-${{ runner.os }}-${{ hashFiles('composer.lock') }}
          restore-keys: |
            composer-${{ runner.os }}-

      - run: composer install --no-interaction --prefer-dist --no-progress

      - run: vendor/bin/pest --ci

The cache step is built from two parts. First, a step with an id asks Composer where its cache lives and writes the answer to $GITHUB_OUTPUT; later steps read it as steps.composer-cache.outputs.dir. Second, actions/cache stores that directory under a key that changes only when composer.lock changes. If the exact key is missing, restore-keys falls back to the most recent cache with the same prefix, so even after a dependency update you start from a nearly complete cache.

Notice that you cache the download cache, not the vendor directory. Installing from a warm download cache is fast, and it keeps the install step honest: composer install still verifies your lock file and recreates vendor from scratch.

Whatever the language, key your cache on the lock file (pom.xml, go.sum, composer.lock), never on a date or a commit hash. A key that changes every run never hits; a key that never changes serves stale dependencies.

Test reports

A red cross on a pull request tells the author that something failed, but not what. You have three common ways to help:

  1. Read the log. Test runners print failures. This is the baseline and costs nothing.
  2. Upload the report as an artifact, as in the Java example. A reviewer can download the JUnit XML or HTML coverage report afterwards.
  3. Publish annotations. Many marketplace actions read JUnit XML files and show failed tests as annotations on the pull request's "Files changed" tab. Choose one that is actively maintained and pin it as described in Securing Your Pipeline.

Go can emit machine-readable output with go test -json, and Pest and PHPUnit can write JUnit XML with --log-junit report.xml. Whichever format you pick, remember the rule from the Java example: reports must be uploaded with if: always() so they exist when the tests fail.

Service containers

Integration tests need real infrastructure: a database, a cache, a message broker. In GitHub Actions you declare these as service containers under a job. The runner starts each one as a Docker container on a private network before your steps begin and stops it when the job ends. Service containers need a Linux runner.

YAML
jobs:
  integration:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: app
          POSTGRES_PASSWORD: app_password
          POSTGRES_DB: app_test
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U app -d app_test"
          --health-interval 5s
          --health-timeout 3s
          --health-retries 10
    env:
      DATABASE_URL: postgres://app:app_password@localhost:5432/app_test
    steps:
      - uses: actions/checkout@v4
      - run: ./run-integration-tests.sh

Two things make this reliable. The first is the health check passed through options. Starting a container is not the same as the database being ready to accept connections; PostgreSQL takes a few seconds to initialize. The runner waits until Docker reports the container as healthy before it runs your first step, so your tests never race the database. The second is the address. When the job runs directly on the runner (as above), the service is reachable at localhost on the port you mapped. When the job itself runs in a container (with container:), the service is reachable by its service name, here postgres, and no port mapping is needed.

The password in this example is a throwaway value for a database that exists for a few minutes. For anything that is not disposable, use a secret, as explained in Secrets, Variables and Environment Variables.

Stand-in: waiting for a healthy service

The runner's wait logic is simple: poll the health command at an interval, count failures, and either start your steps or fail the job. This stand-in simulates it with a fake database that becomes ready after a few seconds of "time". The clock is simulated, so the output is the same on every run.

JS A job that waits for its service container

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second run shows a classic mistake: a health check that gives up too early fails the job even though the database would have been ready a moment later. Choose --health-retries times --health-interval so the total comfortably exceeds your service's worst-case startup time.

Stand-in: how a cache key reacts to the lock file

A cache key is a fingerprint of the lock file, and the runner restores the cache only when the fingerprint matches. The stand-in below uses a simple hash (not the real hashFiles, which hashes file contents with SHA-256 and is richer than this) to show why unchanged dependencies mean a cache hit.

JS Cache keys from lock file content

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Which language needs what

Concern Java Go PHP
Setup action actions/setup-java actions/setup-go shivammathur/setup-php (community)
Dependency cache cache: maven or gradle on by default (go.sum) actions/cache on Composer's cache dir
Cache key file pom.xml / *.gradle* go.sum composer.lock
Typical test command mvn verify go test -race ./... vendor/bin/pest or phpunit
Report to upload target/surefire-reports coverage profile JUnit XML, coverage

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the Java workflow upload test reports with if: always()?

    By default a step is skipped once an earlier step has failed. The reports are most valuable after a failure, so the upload step must run on both success and failure.
  2. 2. Which file should the PHP Composer cache key be based on?

    The lock file changes exactly when the resolved dependencies change. A SHA or a date never repeats, so the cache would never hit.
  3. 3. A job has a PostgreSQL service container without a health check, and the first test sometimes fails with 'connection refused'. What is the likely cause?

    Starting a container is not the same as being ready. A health check makes the runner wait until the database is healthy before it runs your steps.
  4. 4. How do you reach a service container from a step when the job runs directly on the runner (no container: key)?

    When the job runs on the runner host, mapped ports are published on localhost. Only jobs that run inside a container address services by name.
  5. 5. What does go-version-file: go.mod achieve?

    The setup action reads the go directive from the file, so you do not repeat the version in the workflow.

Summary

  • Every language pipeline has the same skeleton: checkout, set up the toolchain, restore the dependency cache, build and test, upload reports.
  • actions/setup-java and actions/setup-go can cache dependencies themselves; for PHP you cache Composer's download directory with actions/cache, keyed on composer.lock.
  • Key caches on lock files, and use restore-keys as a fallback to a recent cache.
  • Upload test reports with if: always() so they exist after failures, and give matrix artifacts unique names.
  • Service containers give integration tests a real database; a health check makes the runner wait until it is ready.
  • On the runner host a service is reached at localhost:<mapped port>; inside a container: job it is reached by its service name.

Next, you will package an application into a container image and publish it from a workflow: Building and Pushing Docker Images.