GitHub Actions Matrix Strategy: Test Across OS and Versions
Run one job across every OS/runtime combination with GitHub Actions matrix strategy: include/exclude, fail-fast, dynamic matrices, and service containers.
Overview
The strategy.matrix block in GitHub Actions turns one job definition into many: you declare axes of values (OS, runtime version, database) and the runner expands them into a Cartesian product, spawning one job per combination. A 3×3 OS/version matrix produces nine jobs from about ten lines of YAML, each with its own logs, status, and retry button, all running in parallel.
That expansion is what makes matrices powerful and expensive at the same time. On private repositories every spawned job bills runner minutes, and Windows minutes cost 2x and macOS minutes 10x what Linux costs. This recipe covers the matrix knobs that matter in practice — include, exclude, fail-fast, max-parallel, continue-on-error, dynamic matrices fed by a previous job — and the failure modes that burn CI budget.
When to Use
- Cross-platform testing (Linux, Windows, macOS): the original use case
- Multi-version testing (Node 18/20/22, Python 3.10/3.11/3.12)
- Testing against several databases or services (PostgreSQL, MySQL, Redis)
- Variant builds (debug/release, feature flags on/off, multi-arch Docker images)
- Monorepos where the list of packages to test changes constantly: use a dynamic matrix
When NOT to Use
- A single platform and version: a plain job is simpler and cheaper
- Combinations that would exceed GitHub’s 256-jobs-per-workflow limit
- When most of the product is redundant: prefer
includeto add just the pairs that matter - When fast feedback beats coverage: every combination multiplies wall time and billed minutes
Solution
The examples build on each other. Start with a one-axis matrix, then layer on a second axis, carve out exceptions with exclude/include, and finish with dynamic matrices and artifacts.
Basic matrix
One axis, three jobs: the smallest useful matrix.
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
Multiple matrix dimensions
Each additional axis multiplies the job count: 3 OS × 3 versions = 9 jobs.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
Exclude specific combinations
exclude removes cells from the product after expansion: cheaper than an if-based skip.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22]
exclude:
# Don't test Node 18 on macOS
- os: macos-latest
node-version: 18
# Don't test Node 22 on Windows
- os: windows-latest
node-version: 22
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
Include additional combinations
include does two different things: when the entry matches an existing combination it merges extra keys into it; when it doesn’t, it appends a whole new job.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, windows-latest]
node-version: [20, 22]
include:
# Add a specific combination with extra config
- os: macos-latest
node-version: 22
experimental: true
# Add extra env vars to an existing combination
- os: ubuntu-latest
node-version: 22
coverage: true
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
- name: Run coverage
if: ${{ matrix.coverage }}
run: npm run test:coverage
Fail-fast and max-parallel
Two knobs that control scheduling: whether one failure cancels the rest, and how many jobs run at once.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false # Don't cancel other jobs on failure
max-parallel: 4 # Run at most 4 jobs in parallel
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [18, 20, 22]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
Matrix with services
Each matrix job gets its own service containers. Using include to carry per-database config keeps the services: block generic.
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
database: [postgres, mysql]
include:
- database: postgres
db-image: postgres:16
db-port: 5432
db-env: |
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: testdb
- database: mysql
db-image: mysql:8
db-port: 3306
db-env: |
MYSQL_USER: test
MYSQL_PASSWORD: test
MYSQL_DATABASE: testdb
MYSQL_ROOT_PASSWORD: root
services:
db:
image: ${{ matrix.db-image }}
env: ${{ matrix.db-env }}
ports:
- ${{ matrix.db-port }}
options: >-
--health-cmd "pg_isready || mysqladmin ping"
--health-interval 5s
--health-timeout 3s
--health-retries 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm test
env:
DB_TYPE: ${{ matrix.database }}
DB_PORT: ${{ matrix.db-port }}
Dynamic matrix from JSON
A prepare job emits a JSON array; the test job feeds it to fromJSON. Useful when the axis lives in a config file or an API response.
jobs:
# Job 1: Generate the list of versions
prepare:
runs-on: ubuntu-latest
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
- uses: actions/checkout@v4
- id: set-matrix
run: |
# Read supported versions from a file
VERSIONS=$(cat .github/supported-versions.json)
echo "matrix=$VERSIONS" >> $GITHUB_OUTPUT
# Job 2: Use the dynamic matrix
test:
needs: prepare
runs-on: ubuntu-latest
strategy:
matrix:
value: ${{ fromJSON(needs.prepare.outputs.matrix) }}
steps:
- uses: actions/checkout@v4
- run: echo "Testing version ${{ matrix.value }}"
Dynamic matrix from package.json
The monorepo pattern: derive the matrix from workspaces so new packages get tested automatically.
jobs:
prepare:
runs-on: ubuntu-latest
outputs:
packages: ${{ steps.set-matrix.outputs.packages }}
steps:
- uses: actions/checkout@v4
- id: set-matrix
run: |
# Extract package names from workspaces
PACKAGES=$(node -e "
const pkg = require('./package.json');
const names = pkg.workspaces.map(w => w.replace('packages/', ''));
console.log(JSON.stringify(names));
")
echo "packages=$PACKAGES" >> $GITHUB_OUTPUT
test:
needs: prepare
runs-on: ubuntu-latest
strategy:
matrix:
package: ${{ fromJSON(needs.prepare.outputs.packages) }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: cd packages/${{ matrix.package }} && npm test
Matrix with continue-on-error for experimental
Mark bleeding-edge versions as non-blocking without allow-failure hacks: the job runs but doesn’t gate the workflow.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node-version: [20, 22]
include:
- os: ubuntu-latest
node-version: 23
experimental: true
continue-on-error: ${{ matrix.experimental == true }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- run: npm ci
- run: npm test
Matrix with build artifacts
Each leg uploads a named artifact; a downstream job collects all of them for a release.
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
include:
- os: ubuntu-latest
artifact: linux-x64
- os: windows-latest
artifact: windows-x64
- os: macos-latest
artifact: macos-x64
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: build-${{ matrix.artifact }}
path: dist/
release:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v4
with:
path: artifacts/
- run: ls -la artifacts/
Companion files: the github-actions-matrix-strategy companion repo has a runnable .github/workflows/ setup (static matrix, dynamic matrix, services matrix) plus supported-versions.json, so you can fork it and watch the jobs spawn for real.
Explanation
How the matrix expands
strategy.matrix computes the Cartesian product of every axis you declare. os: [a, b, c] times node-version: [x, y, z] yields nine job instances, and each matrix.<key> resolves to that job’s cell. The expansion happens server-side: GitHub creates the job list before any runner starts, which is why a typo in an axis name fails the whole workflow rather than one job.
exclude filters that product after expansion: each entry must match all declared keys of a cell to remove it. include then applies: an include entry whose declared keys match an existing cell merges its extra keys into that cell (that’s how coverage: true reaches only ubuntu-latest + node 22 above); an entry that doesn’t match appends a brand-new job. exclude wins over include if both target the same cell.
The matrix context is available in name, if, run, with, env, and services, so name: Test (${{ matrix.os }}, Node ${{ matrix.node-version }}) produces readable job labels like “Test (ubuntu-latest, Node 22)”. Undefined keys on include-appended jobs evaluate to empty/falsy rather than erroring, which is why if: ${{ matrix.coverage }} is safe.
What a matrix costs
Every cell is a real job with real minutes. On private repositories the runner multipliers matter: a 3×3 matrix on Linux, Windows, and macOS bills roughly 3×1 + 3×2 + 3×10 = 39 Linux-equivalent minutes per test minute. GitHub caps a workflow at 256 jobs per matrix expansion; beyond that you split the matrix across several jobs or generate it dynamically. max-parallel doesn’t reduce cost; it only throttles concurrency, which helps with shared runner pools, database services that can’t take 9 simultaneous connections, or API rate limits.
An empty matrix is a quiet killer: if a dynamic fromJSON expression resolves to [], the job simply never runs — no error, no jobs in the UI. Guard it with a fallback like ${{ fromJSON(needs.prepare.outputs.matrix) || fromJSON('["default"]') }} or fail loudly in the prepare step.
Variants
Matrix for Python projects
Same shape, different setup action — 3.10 parses as 3.1 unless you quote the version strings.
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: pip install -e ".[dev]"
- run: pytest --cov
Matrix for Java projects
Two independent axes: JDK and Gradle version. setup-gradle handles wrapper vs. version resolution.
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
java-version: [17, 21]
gradle-version: [7, 8]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java-version }}
distribution: temurin
- uses: gradle/actions/setup-gradle@v3
with:
gradle-version: ${{ matrix.gradle-version }}
- run: gradle test
Matrix for Docker multi-arch builds
One leg per platform produces per-arch image tarballs you can merge into a manifest later. The distroless multi-stage recipe pairs well for the image side.
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
platform: [linux/amd64, linux/arm64, linux/arm/v7]
steps:
- uses: actions/checkout@v4
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v5
with:
context: .
platforms: ${{ matrix.platform }}
tags: my-app:latest-${{ matrix.platform }}
cache-from: type=gha
cache-to: type=gha,mode=max
outputs: type=docker,dest=artifact-${{ matrix.platform }}.tar
- uses: actions/upload-artifact@v4
with:
name: docker-${{ matrix.platform }}
path: artifact-${{ matrix.platform }}.tar
Best Practices
- Name jobs with matrix context (
name: Test (Node ${{ matrix.node-version }} on ${{ matrix.os }})) so the checks list tells you which cell failed without opening logs. - Set
fail-fast: falsefor compatibility testing: you’re collecting a pass/fail matrix, not guarding a deploy. Keep the defaulttruefor deploy-gating jobs. - Use
includefor exceptions and extras instead of growing a new axis: one-off combos shouldn’t multiply the whole product. - Use
excludeto drop known-broken or redundant cells, and leave a comment saying why each exclusion exists. - Scope cache keys per cell (
key: ${{ runner.os }}-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}) or jobs on different OSes poison each other’s caches. - Prefer dynamic matrices in monorepos; a static list of packages goes stale within a sprint.
- For matrices that feed shared logic, reusable workflows let you call one matrix workflow from many repos.
Common Mistakes
- Leaving
fail-fastat its defaulttrue. One flaky macOS leg cancels the other eight jobs and you lose the pass/fail picture you ran the matrix for. Setfail-fast: falseon coverage matrices. - Letting the product explode. 3 OS × 3 runtimes × 2 databases = 18 jobs per commit, and on private repos macOS legs bill 10x. Trim with
excludeor drop axes. - Unquoted version numbers.
node-version: [3.10]parses as the float3.1andsetup-node/setup-pythoninstall the wrong runtime — quoting them (["3.10", "3.11"]) fixes it. - Sharing one cache key across cells.
cache: npmalone keys on the lockfile; addrunner.osand the matrix axis to the key or the Windows legs restore a Linux cache and recompile native modules anyway. - Hardcoding the axis when a config file already knows it. Supported versions and workspace packages drift; a
preparejob emitting the matrix keeps one source of truth. - Assuming
includeappends. It merges into matching cells — anincludeentry that accidentally matches an existing combination silently adds keys to it instead of creating the new job you expected.
Further Reading
- GitHub Docs — Running variations of jobs in a workflow (matrix): the reference for
matrix,include,exclude,fail-fast, andmax-paralleloptions. - GitHub Docs — Contexts reference: every place
matrix.*and friends are legal (if,env,with,name,services). - GitHub Docs — Billing for GitHub Actions: the per-OS minute multipliers that make big matrices expensive.
- Starter workflows: official matrices for Node, Python, Go, .NET — worth diffing against yours.
- Internal: the base GitHub Actions recipe for triggers and job anatomy, reusable workflows for sharing a matrix across repos, and the CI/CD GitHub Actions guide for the wider pipeline.
Frequently Asked Questions
What does strategy.matrix do in GitHub Actions?
It expands every combination of the axes you declare into a separate job instance. os: [3 values] × node: [3 values] spawns nine parallel jobs, each seeing its own cell through the matrix.* context.
Does one failing matrix job cancel the others?
Yes, by default: fail-fast: true cancels all in-progress siblings the moment one leg fails. Set fail-fast: false when you want the full pass/fail matrix, which is most of the time.
How many jobs can a matrix create and what does it cost?
GitHub caps expansion at 256 jobs per workflow run. Cost is combinations × minutes × OS multiplier: on private repos Windows bills 2x and macOS 10x Linux minutes, so keep macOS legs minimal.
When should I use include instead of adding a matrix axis?
Whenever the extra cell doesn't deserve a whole dimension. include adds one combination (or merges keys into a matching one) without multiplying the rest of the product.
Can the matrix come from somewhere other than the YAML?
Yes: a previous job can output a JSON array that the matrix consumes via fromJSON(needs.<job>.outputs.<name>). That's the standard pattern for monorepo package lists and config-driven version sets.
What happens if a dynamic matrix resolves to an empty array?
The job silently produces zero runs: nothing fails, nothing shows up. Fail explicitly in the prepare job or provide a fallback expression so an empty matrix is a visible error, not a skipped test suite.
Related Resources
GitHub Actions Workflow Examples: CI/CD, Matrix & Secrets
How to build and deploy with GitHub Actions using workflows, matrices, caching, secrets, environments, and reusable workflows.
RecipeShare Workflow Logic with GitHub Actions Reusable Workflows
How to create and consume reusable workflows in GitHub Actions, covering inputs, secrets, conditional jobs, matrix strategy, and organization-wide sharing.
RecipeCI/CD Pipeline Setup
Set up automated CI/CD pipelines for testing, building, and deploying applications with GitHub Actions and what works.
GuideComplete Guide to CI/CD with GitHub Actions
Build CI/CD pipelines from scratch with GitHub Actions. Covers workflows, runners, matrix builds, caching, secrets, environments, deployment strategies, and reusable workflows.
RecipeTeam Git Workflow: Feature Branches, PRs and Clean History
A practical Git workflow for teams: feature branches, pull requests, conventional commits, and how to pick the right branching model.
RecipeDistroless Docker Images with Multi-Stage Builds
Build minimal, shell-free production images by pairing multi-stage builds with distroless bases — Go, Node.js, Python, and Java examples.