All code helpers
DevOpsYAML

GitHub Actions CI: lint, test, build and push to GHCR

Run checks on every pull request, and on main build a Docker image and push it to GitHub Container Registry with layer caching. No long-lived registry credentials needed.

#github-actions#ci#docker#ghcr
.github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main]
  pull_request:

# Cancel superseded runs on the same branch or PR
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npm run lint
      - run: npm test --if-present
      - run: npm run build

  image:
    needs: check
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
          tags: |
            type=sha
            type=raw,value=latest
      - uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

How it works & gotchas

  • 01GITHUB_TOKEN with packages: write is enough to push to GHCR. Permissions are granted per job, so the check job can't push anything.
  • 02type=sha tags every image with the commit SHA. Deploy by SHA, not latest, so rollbacks are a one-line change.
  • 03cache-from/cache-to: type=gha stores Docker layers in the Actions cache. Unchanged dependency layers are reused across runs.
  • 04Pull requests from forks don't receive secrets or write tokens, which is why the image job only runs on pushes to main.

Need this wired into a real system?

We build and harden production software end to end.

Talk to an engineer