# 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.

URL: https://levelrail.com/learn/ci-cd/build-and-push-docker-image-to-ghcr/
Updated: 2026-11-27

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](https://levelrail.com/learn/glossary/#registry)) concept is in [Image and container registry explained](https://levelrail.com/learn/docker/image-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](https://levelrail.com/learn/ci-cd/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](https://levelrail.com/learn/ci-cd/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](https://levelrail.com/learn/ci-cd/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](https://levelrail.com/learn/ci-cd/rollback-and-release-strategy-in-a-pipeline/)).

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `denied: permission_denied: write_package` | Token lacks packages: write or package not linked | Add the permission, check package access |
| `invalid reference format: repository name must be lowercase` | Capital letters in owner or name | Lowercase the image name |
| `unauthorized` on `docker pull` | Not logged in or token lacks read:packages | Run docker login ghcr.io with a read token |
| `manifest unknown` | Tag does not exist | List tags on the package page and copy one |
| `no matching manifest for linux/arm64` | Image built for amd64 only | Build with the right platform |
| `Error: Cannot perform an interactive login from a non TTY device` | Missing --password-stdin | Pipe the token in |
| Push step skipped on pull requests | Trigger or push flag excludes PRs | Intended, 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
```

## Related lessons

- [Image and container registry explained](https://levelrail.com/learn/docker/image-container-registry-explained/)): what a registry stores and how tags work.
- [Write your first Dockerfile](https://levelrail.com/learn/docker/write-your-first-dockerfile/)): the file this workflow builds.
- [Multi-stage Docker builds](https://levelrail.com/learn/docker/multi-stage-docker-builds/)): smaller images to push.
- [Deploy over SSH from GitHub Actions](https://levelrail.com/learn/ci-cd/deploy-over-ssh-from-github-actions/)): the step that pulls and runs the image.
- [Update a container to a new image](https://levelrail.com/learn/docker/update-a-container-to-a-new-image/)): what happens on the server after the pull.

## Next

Continue with [Deploy over SSH from GitHub Actions](https://levelrail.com/learn/ci-cd/deploy-over-ssh-from-github-actions/)).

## 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

- [GitHub Docs, working with the Container registry](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
- [Docker Docs, GitHub Actions for building images](https://docs.docker.com/build/ci/github-actions/)
