basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Building images in GitHub Actions for GHCR: tags, cache, private packages

    Build a Docker image in GitHub Actions after checks pass and push it to GitHub Container Registry (ghcr.io) with latest and sha-<commit> tags, so the server only pulls the finished image. Building on a 2 GB VPS eats up to 700 MB of RAM and crowds neighboring services; in Actions it runs on a separate machine and skips publishing if checks fail.

    How the pipeline works

    Building a site or app directly on a production VPS is risky: a Node frontend build or dependency compilation takes 700 MB of RAM or more. On a 2 GB server, that pushes neighboring containers and daemons into swap or triggers the OOM killer. You also end up keeping source code, compilers, and build keys on the server.

    Instead, GitHub Actions builds the image from the repository’s Dockerfile (Multi-stage build) and publishes it to GitHub Container Registry (ghcr.io). The server only pulls the ready image:

    git push to main
          │
          ▼
    GitHub Actions: job check (types, tests, linter)
          │ pass
          ▼
    GitHub Actions: job image (Dockerfile + type=gha cache)
          │ push via secrets.GITHUB_TOKEN (packages: write)
          ▼
    GHCR: ghcr.io/example-user/site:latest and :sha-a1b2c3d
          │ docker compose pull (classic token read:packages)
          ▼
    server web1: docker compose up -d

    Inside Actions you don’t need a separate publishing token: the built-in secrets.GITHUB_TOKEN pushes to GHCR once the job declares packages: write. Pull requests run only check, so untested code never reaches the registry. Every publish writes two tags: latest, updated on each build, and sha-<7-char commit hash> for rollbacks. BuildKit layer cache lives in the Actions cache (type=gha), so subsequent runs reuse dependency layers.

    Setup

    This assumes a working Dockerfile is already at the root of example-user/site (Multi-stage build).

    1. Add the workflow to .github/workflows/image.yml

      name: image
      
      on:
        push:
          branches: [main]
        pull_request:
        workflow_dispatch:
      
      concurrency:
        group: image-${{ github.ref }}
        cancel-in-progress: true
      
      jobs:
        check:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v7
            - uses: actions/setup-node@v7
              with:
                node-version: 24.22.1
                cache: npm
            - run: npm ci
            - run: npm run check
            - run: npm test
      
        image:
          needs: check
          if: github.event_name != 'pull_request'
          runs-on: ubuntu-latest
          permissions:
            contents: read
            packages: write
          steps:
            - uses: actions/checkout@v7
            - uses: docker/setup-buildx-action@v4
            - uses: docker/login-action@v4
              with:
                registry: ghcr.io
                username: ${{ github.actor }}
                password: ${{ secrets.GITHUB_TOKEN }}
            - id: meta
              uses: docker/metadata-action@v6
              with:
                images: ghcr.io/${{ github.repository }}
                tags: |
                  type=raw,value=latest
                  type=sha
            - uses: docker/build-push-action@v7
              with:
                context: .
                push: true
                tags: ${{ steps.meta.outputs.tags }}
                labels: ${{ steps.meta.outputs.labels }}
                cache-from: type=gha
                cache-to: type=gha,mode=max

      What each block does:

      • concurrency with cancel-in-progress: true cancels an in-flight run when a newer commit lands on the same branch, so an older build can’t overwrite latest on top of a newer one.
      • workflow_dispatch adds a “Run workflow” button in the Actions tab, letting you rebuild without pushing a commit — for example, after changing a repository variable.
      • needs: check and if: github.event_name != 'pull_request' keep broken code and draft branches out of the registry.
      • permissions grants minimum access only to the image job: read repository contents and write packages.
      • docker/metadata-action lowercases the repository name, emits the latest and sha-<7 chars> tags, and sets the org.opencontainers.image.source OCI label that links the package to the repository on GitHub.

      If the build needs non-secret parameters such as an analytics ID, store them under Settings, Secrets and variables, Actions, Variables and pass build-args: PUBLIC_ANALYTICS_ID=${{ vars.ANALYTICS_ID }}. Never put secrets in build-args — they persist in image layer history; use BuildKit secrets instead (Build secret via --secret).

    2. Push to main and check the package in GHCR

      git add .github/workflows/image.yml
      git commit -m "ci: build image to ghcr"
      git push

      Open the Actions tab on GitHub: check runs first, then image. Once the run turns green, the site package appears in the Packages sidebar of the repository (or under your profile’s Packages tab) with two tags: latest and sha-<commit>.

      New packages start private. If the repository is public and anyone can pull the image without signing in, change visibility to Public in Package settings (Danger Zone, Change visibility) — then skip steps 3 and 4.

    3. Create a read-only token for packages

      A private package requires a dedicated token for the server. Open your GitHub profile Settings (not repository settings), Developer settings, Personal access tokens, Tokens (classic), Generate new token (classic):

      • grant a single scope — read:packages: the server can only pull images, with no code access and no ability to push packages (Each key and token grants one access);
      • set an expiration date (say, one year) and note when to rotate it.

      ghcr.io requires a classic token: fine-grained tokens don’t support GHCR package permissions.

    4. Log in to GHCR on the server

      Sign in to the registry on web1:

      docker login ghcr.io -u example-user

      Docker prompts for the password (paste the token there), keeping it out of ~/.bash_history and the process list (Keep passwords out of command arguments). Credentials are saved to ~/.docker/config.json for whichever user runs the command.

      If updates on the server run as root (such as a systemd timer in Deploy without SSH), run sudo docker login ghcr.io -u example-user: otherwise root won’t see the regular user’s login and will get unauthorized.

    5. Reference the image in compose.yaml and wire up rollbacks

      Point /opt/site/compose.yaml at the GHCR image with a variable tag:

      services:
        web:
          image: ghcr.io/example-user/site:${IMAGE_TAG:-latest}
          restart: unless-stopped

      After the Actions run goes green, update the stack on the server:

      cd /opt/site && docker compose pull && docker compose up -d

      If a new build breaks the site, roll back to the previous commit without rebuilding: grab its sha-a1b2c3d tag from the package page on GitHub, add IMAGE_TAG=sha-a1b2c3d to /opt/site/.env, and run docker compose up -d. To return to latest, remove IMAGE_TAG from .env and run docker compose pull && docker compose up -d again.

      To avoid SSHing in for every release, let Renovate manage digest-pinned tags while a timer-driven deploy script restarts stacks automatically (Deploy without SSH).

    If it doesn’t work

    denied: permission_denied: write_package when pushing the image in Actions

    Cause
    The image job lacks packages: write, or a package with that name already exists under your account and isn’t linked to this repository.
    Fix
    Check the permissions: packages: write block in the workflow. If the package existed beforehand, open it under Packages on GitHub, go to Package settings, and add the repository with the Write role under Manage Actions access.

    docker pull ghcr.io/example-user/site:latest on the server returns denied or unauthorized

    Cause
    New GHCR packages are private and the server isn’t logged into ghcr.io, or the token expired, or it lacks read:packages. Another common cause: login ran as a regular user while pull runs as root.
    Fix
    Run docker login ghcr.io -u example-user (or sudo docker login … for root) with a classic token carrying read:packages (step 4). If the image can be public, switch package visibility to Public in Package settings.

    invalid tag "ghcr.io/Example-User/Site:latest": repository name must be lowercase

    Cause
    The GitHub owner or repository name contains uppercase letters, and Docker registries only accept lowercase.
    Fix
    docker/metadata-action lowercases the name automatically. If you assemble the tag string without it, lowercase ${{ github.repository }} explicitly.

    Every Actions run rebuilds all layers from scratch

    Cause
    BuildKit caching (cache-from and cache-to) isn’t configured, or COPY . . sits above dependency installation in the Dockerfile.
    Fix
    Add cache-from: type=gha and cache-to: type=gha,mode=max to build-push-action and check instruction order in the Dockerfile (Multi-stage build).

    An Actions run cancels itself with status Cancelled right after a new commit

    Cause
    concurrency is set with cancel-in-progress: true, and a second push hit the same branch while the first commit was still building.
    Fix
    Working as intended: cancelling the older run saves Actions minutes and stops an earlier build from overwriting latest.

    docker compose pull succeeded on the server, but the old image keeps running

    Cause
    docker compose pull only downloads the image to disk; it doesn’t recreate the container. Or .env still pins an old sha-… tag in IMAGE_TAG.
    Fix
    Run docker compose up -d after pull. If IMAGE_TAG is set in .env, remove it so Compose switches back to latest.

    How to check

    Verify that the server pulls the image and sees its architecture and digest:

    docker pull ghcr.io/example-user/site:latest
    docker image inspect ghcr.io/example-user/site:latest --format '{{.Architecture}} {{index .RepoDigests 0}}'
    # amd64 ghcr.io/example-user/site@sha256:...

    Confirm the commit-tagged image exists in the registry (so rollbacks will work):

    docker manifest inspect ghcr.io/example-user/site:sha-a1b2c3d | head -5

    You should see the start of the manifest JSON without a no such manifest error.

    Confirm the server’s token has no write access — a test push must be rejected:

    docker tag ghcr.io/example-user/site:latest ghcr.io/example-user/site:perm-test
    docker push ghcr.io/example-user/site:perm-test
    # denied: permission_denied: write_package
    docker rmi ghcr.io/example-user/site:perm-test