Chapter 12 · Lesson 4 of 10
CI/CD and automation

Build and push a Docker image to GHCR with GitHub Actions

GHCR is GitHub's container registry at ghcr.io, and a workflow can log in with GITHUB_TOKEN, build an image and push it with tags derived from the commit or version.

By the end you will

Publish a Docker image to ghcr.io from a workflow with sha and version tags, then pull it on a server with a read-only token.

Time
20 min
Level
Intermediate
Check
4 questions
You need
  • A GitHub repository with a Dockerfile
  • Docker installed on the server that will pull the image

From a commit to an image on your server

The workflow builds and pushes a tagged image to GHCR, and the server pulls that same tag to run it.
  1. A push to the main branch starts a GitHub Actions workflow on a runner.
  2. The runner logs in with GITHUB_TOKEN, builds the image and pushes it with a commit tag.
  3. Your server logs in with a read-only token and pulls that exact tag.
  4. The server replaces the old container with one started from the new image.
Static diagram
  1. RepositorypushActions runner
  2. Actions runnerbuild and pushGHCR
  3. Your serverpullGHCR
  4. GHCRnew containerYour server

After tests pass, the next stage is to build the Docker image once and store it in a registry, so any server can pull it. GitHub Container Registry (GHCR) is built in, needs no extra account and accepts the workflow’s own GITHUB_TOKEN. This lesson builds the workflow, explains the tags, and shows how a server pulls the result. The registry concept is in Image and container registry explained.

How it works#

The job logs in to ghcr.io, computes tags from the git context, builds the image with Buildx and pushes it. The image lives at ghcr.io/OWNER/IMAGE:TAG. A later deploy stage, on a server or another job, pulls that exact tag. This is the “build once, deploy many” idea from CI/CD pipeline stages explained.

Three actions do the work:

  • docker/login-action@v3 authenticates to the registry.
  • docker/metadata-action@v5 turns the git ref into a list of tags and labels.
  • docker/build-push-action@v6 builds and pushes.

Step 1: Write the workflow#

Create .github/workflows/image.yml. Replace the image name if yours differs:

yaml
name: image

on:
  push:
    branches: [main]
    tags: ['v*']

permissions:
  contents: read
  packages: write

jobs:
  build:
    runs-on: ubuntu-latest
    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 }}

      - name: Lowercase image name
        run: echo "IMAGE=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_ENV"

      - id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE }}
          tags: |
            type=sha
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}

      - uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

The permissions block gives the token packages: write to push and contents: read to check out code, and nothing else. The ${GITHUB_REPOSITORY,,} expansion lowercases the owner/repo string in bash.

Step 2: Understand the tags#

docker/metadata-action@v5 builds the tag list from rules:

  • type=sha creates a tag from the short commit SHA, such as sha-1a2b3c4. Every push gets one, and it never changes. Deploy this one.
  • type=semver,pattern={{version}} creates 1.2.0 when you push a git tag v1.2.0.
  • type=semver,pattern={{major}}.{{minor}} creates 1.2, a convenience tag that moves with patch releases.

Pushes to main produce a SHA tag. Pushes of a version tag produce the semver tags plus a SHA tag. See Version and tag releases for the tagging side. Avoid depending on a moving tag like latest for production, because you cannot tell which commit it holds.

Step 3: Name the image in lowercase#

Registry repository names must be lowercase. A GitHub owner such as MyOrg makes ghcr.io/MyOrg/app invalid, and the push fails with an invalid reference format error. The lowercase step above avoids that for any repository name. Check the final name in the build log, in the exporting to image lines.

Step 4: Set package visibility#

A package pushed by a workflow starts private and is linked to the repository. Open the package from your profile or organization, then Package settings. You can make it public if the image is meant for everyone, or keep it private and grant access. Private is the safer default for application images. Never bake secrets into an image, because anyone who can pull it can read every layer.

Step 5: Pull on the server with a read-only token#

On GitHub, create a personal access token (classic) with only the read:packages scope, or a fine-grained token that can read the package. Store it on the server in a file readable only by the deploy user, then log in:

bash
cat ~/.ghcr-token | docker login ghcr.io -u YOUR_GITHUB_USERNAME --password-stdin
docker pull ghcr.io/myorg/myapp:sha-1a2b3c4

--password-stdin keeps the token out of your shell history and process list. Replace the username, token file and image name with your own. The token should not be able to push, so a stolen server cannot overwrite your images. How the deploy step runs this is covered in Deploy over SSH from GitHub Actions.

Check it worked#

In the workflow log, the build-push-action step ends with lines showing the pushed tags. On GitHub, the repository page lists the package under Packages with the new tags. On the server:

bash
docker pull ghcr.io/myorg/myapp:sha-1a2b3c4
docker image ls ghcr.io/myorg/myapp

You should see the tag listed. Run it with docker run --rm and confirm it starts.

Edge cases and gotchas#

  • Pull requests should not push. The workflow above triggers on push to main and tags only. If you also build on pull requests to test the Dockerfile, set push: false there, since fork PRs have no write access anyway.
  • Package not linked to the repo. The first push from another tool may create an unlinked package, and the workflow token then cannot write to it. Push from the workflow first, or grant the repository access in package settings.
  • Tokens in logs. docker/login-action masks the password. Do not echo it yourself.
  • Multi-architecture. Building for ARM servers needs a platforms setting and QEMU. Check your server architecture with uname -m before assuming amd64.
  • Large contexts. A missing .dockerignore sends node_modules and .git to the builder. Add one.
  • Retention. Old SHA tags pile up. Clean them on a schedule, but never delete the tag a server currently runs. See Rollback and release strategy.

Troubleshooting#

SymptomLikely causeFix
denied: permission_denied: write_packageToken lacks packages: write or package not linkedAdd the permission, check package access
invalid reference format: repository name must be lowercaseCapital letters in owner or nameLowercase the image name
unauthorized on docker pullNot logged in or token lacks read:packagesRun docker login ghcr.io with a read token
manifest unknownTag does not existList tags on the package page and copy one
no matching manifest for linux/arm64Image built for amd64 onlyBuild with the right platform
Error: Cannot perform an interactive login from a non TTY deviceMissing —password-stdinPipe the token in
Push step skipped on pull requestsTrigger or push flag excludes PRsIntended, build without pushing

Quick reference#

bash
# server side
cat ~/.ghcr-token | docker login ghcr.io -u USERNAME --password-stdin
docker pull ghcr.io/owner/image:sha-1a2b3c4
yaml
permissions:
  contents: read
  packages: write

Next#

Continue with Deploy over SSH from GitHub Actions.

Check what you learned4 questions
1Which permission lets the GITHUB_TOKEN push a package?
2Your repository is MyOrg/MyApp. What is a valid image name?
3Why tag images with the commit SHA?
4What scope should the server's pull token have?

Frequently asked questions

How do I push a Docker image to GitHub Container Registry from Actions?

Log in with docker/login-action@v3 using registry ghcr.io, your username and the GITHUB_TOKEN, give the job packages: write, then run docker/build-push-action@v6 with push set to true and a ghcr.io/OWNER/IMAGE tag.

Why must the GHCR image name be lowercase?

Registry repository names must be lowercase, but GitHub owner and repository names can contain capitals. If yours do, lowercase the name before using it in a tag, or the push fails with an invalid reference format error.

Is a GHCR package public or private by default?

A package pushed from a workflow is private unless you change its visibility in the package settings. Private images need a login to pull.

How does a server pull a private GHCR image?

Create a personal access token with only the read:packages scope, then run docker login ghcr.io -u USERNAME --password-stdin on the server. Use a token that only reads.

Sources

View MD Edit
Share
Helpful?
Progress is saved in this browser only.

Keep going: guides and tutorials

View MD Edit
Share
Helpful?
Run this on your own server

Levelrail deploys apps from git with health-checked releases and one-click rollback.

docker pull ghcr.io/glincker/levelrail:latest Install Levelrail From GLINR Studios