CI/CD and automation · Intermediate · 17 min
Build and push a container image to GitHub Container Registry from Actions
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · GitHub Actions (docker/build-push-action v7, metadata-action v6, setup-buildx-action v4, login-action v4, setup-qemu-action v4, actions/checkout v7) · actionlint 1.7.12 · hadolint 2.15.1
You will have a GitHub Actions workflow that builds a small Node.js image for amd64 and arm64, tags it from Git refs, caches its layers, attaches provenance and an SBOM, pushes it to ghcr.io only from main and version tags, and hands the next job the image pinned by digest.
On this page
A container image that you build on your laptop and push by hand is hard to trust later. You cannot say which commit it came from, the tag latest moves under you, and an arm64 server pulls an image that only runs on amd64. Building the image in CI fixes all three, as long as the workflow is set up with care.
In this tutorial you will write one workflow for a small Node.js service. It builds the image on every pull request without pushing it, and on main and on version tags it logs in to GitHub Container Registry (ghcr.io) with the token GitHub gives each run, pushes an image for both linux/amd64 and linux/arm64, reuses layers from earlier runs and attaches a record of how the image was built. The last job receives the image by its digest, an address that can never point at different bytes.
You will check each version of the files on your own machine with two linters: hadolint for the Dockerfile and actionlint for the workflow. The build itself happens on GitHub after you push.
Before you start, create an empty repository on GitHub (no README, so the first push is simple) and check that Actions is enabled under Settings, Actions. The repository matters more than usual here: the image is published as ghcr.io/<owner>/<repository>, and the package takes its visibility from it, so a public repository gives a public image.
Everything lives in a throwaway folder, ~/ghcr-demo, which you connect to that repository before the first push. In your own project, put the workflow next to your existing Dockerfile instead.
Step 1 · Create the service, its Dockerfile and hadolint
Install Git if you do not have it, then make the folder, turn it into a Git repository and add a service with no dependencies, so the image build has nothing to download beyond the base image:
sudo apt update
sudo apt install -y git
mkdir -p ~/ghcr-demo/.github/workflows
cd ~/ghcr-demo
git init -b main
cat > package.json <<'JSON'
{
"name": "ghcr-demo",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "node server.js"
}
}
JSON
cat > server.js <<'JS'
import { createServer } from 'node:http'
const port = Number(process.env.PORT ?? 3000)
createServer((req, res) => {
res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' })
res.end(`ghcr-demo running on ${process.arch}\n`)
}).listen(port, () => {
console.log(`listening on ${port}`)
})
JS
cat > .dockerignore <<'TXT'
.git
.github
node_modules
TXT
cat > Dockerfile <<'DOCKERFILE'
FROM node:26-slim
WORKDIR /app
ENV NODE_ENV=production
COPY --chown=node:node package.json server.js ./
USER node
EXPOSE 3000
CMD ["node", "server.js"]
DOCKERFILEThe service prints the processor architecture it runs on, which makes it easy to see later that the arm64 and amd64 variants are both real. The image runs as the unprivileged node user that the official base image provides. For a fuller Dockerfile with dependencies, see the Dockerfile tutorial linked at the end.
Install hadolint, a linter for Dockerfiles, from its GitHub releases (version 2.15.1 here). On macOS, brew install hadolint does the same. On Linux, download it and check it against the published checksums:
sudo apt update
sudo apt install -y curl ca-certificates
case "$(uname -m)" in
x86_64) HL_ARCH=x86_64 ;;
aarch64) HL_ARCH=arm64 ;;
*) echo "unsupported architecture: $(uname -m)"; false ;;
esac
mkdir -p ~/.local/bin /tmp/hadolint-dl
cd /tmp/hadolint-dl
curl -fsSLO "https://github.com/hadolint/hadolint/releases/download/v2.15.1/hadolint-linux-${HL_ARCH}"
curl -fsSLO "https://github.com/hadolint/hadolint/releases/download/v2.15.1/checksums.sha256"
sha256sum --ignore-missing -c checksums.sha256
install -m 755 "hadolint-linux-${HL_ARCH}" ~/.local/bin/hadolint
cd ~/ghcr-demo
rm -rf /tmp/hadolint-dl
export PATH="$HOME/.local/bin:$PATH"sha256sum prints hadolint-linux-x86_64: OK (or the arm64 name). A binary installed this way gets no updates from apt; to upgrade, run the same lines with the newer version number from github.com/hadolint/hadolint/releases.
Check it worked
Lint the Dockerfile, then lint a copy that uses a moving tag, to see what a failure looks like:
hadolint --version
hadolint Dockerfile && echo "Dockerfile is clean"
sed 's/^FROM node:26-slim$/FROM node:latest/' Dockerfile > /tmp/Dockerfile.latest
if hadolint /tmp/Dockerfile.latest; then
echo "expected hadolint to flag the latest tag"; false
else
echo "hadolint flagged the moving base image tag"
fi
rm /tmp/Dockerfile.latestThe version line names 2.15.1, the real Dockerfile prints Dockerfile is clean, and the copy produces a DL3007 warning about latest followed by hadolint flagged the moving base image tag.
Step 2 · Install actionlint and decide when the workflow runs
Install actionlint from its GitHub releases (version 1.7.12 here). On macOS, brew install actionlint. On Linux:
case "$(uname -m)" in
x86_64) AL_ARCH=amd64 ;;
aarch64) AL_ARCH=arm64 ;;
*) echo "unsupported architecture: $(uname -m)"; false ;;
esac
mkdir -p /tmp/actionlint-dl
cd /tmp/actionlint-dl
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_${AL_ARCH}.tar.gz"
curl -fsSLO "https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_checksums.txt"
sha256sum --ignore-missing -c actionlint_1.7.12_checksums.txt
tar -xzf "actionlint_1.7.12_linux_${AL_ARCH}.tar.gz" -C ~/.local/bin actionlint
cd ~/ghcr-demo
rm -rf /tmp/actionlint-dl
actionlint -version | head -n 1sha256sum prints the archive name followed by OK. Like hadolint, this copy gets no updates from apt; to upgrade, run the same lines with the newer version number from github.com/rhysd/actionlint/releases.
Before writing any build steps, settle the triggers, because they decide what gets pushed:
pushtomain: build and push. These images get the moving tagedgeand asha-tag.pushof a tag such asv1.4.2: build and push a release, tagged1.4.2,1.4andlatest.pull_requestintomain: build only. This proves the Dockerfile still builds for both platforms, without putting unreviewed code in the registry. Pull requests from forks also get a read-only token, so a push from them would fail anyway.
The token GitHub creates for each run, GITHUB_TOKEN, can push to ghcr.io only when the workflow asks for packages: write. Grant it on the one job that needs it and keep the workflow default at read-only.
Check it worked
actionlint -version | head -n 1 | grep -F 1.7.12 && echo "actionlint 1.7.12 is on PATH"The last line reads actionlint 1.7.12 is on PATH. If your shell cannot find it, run export PATH="$HOME/.local/bin:$PATH" and try again.
Step 3 · Write the build job with tags from Git refs
Create the workflow. It sets up emulation so an amd64 runner can build arm64, sets up Buildx, logs in except on pull requests, works out the tags and builds:
cat > .github/workflows/image.yml <<'YAML'
name: Container image
on:
push:
branches: [main]
tags: ['v*.*.*']
pull_request:
branches: [main]
permissions:
contents: read
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v7
- name: Set up QEMU for arm64 builds
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Work out tags and labels
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=edge,branch=main
type=sha
type=ref,event=pr
- name: Build, and push outside pull requests
id: build
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
annotations: ${{ steps.meta.outputs.annotations }}
YAMLWhat the tag rules produce, for an acme/ghcr-demo repository (metadata-action lowercases the owner and name, which ghcr.io requires):
- A push to
mainat commit3f9c2abgivesedgeandsha-3f9c2ab. - A push of the tag
v1.4.2gives1.4.2,1.4,latestand asha-tag. - Pull request 12 gives
pr-12and asha-tag, built but not pushed.
latest is not in the list of rules. metadata-action adds it on its own for semver and tag events, so it always means "the newest release", never "whatever was merged last". If you want a {{major}} tag such as 1, add type=semver,pattern={{major}}; leave it out for projects still on 0.x, where it would follow breaking changes.
metadata-action also writes labels, including org.opencontainers.image.source pointing at your repository. That label is what links the package on GitHub to the repository, and a package published from a workflow with GITHUB_TOKEN takes the repository's visibility: public repository, public image.
Check it worked
actionlint .github/workflows/image.yml
echo "actionlint exit code: $?"No messages and exit code 0. actionlint has checked the steps.meta.outputs references, the expressions in if and push, and that secrets.GITHUB_TOKEN is used in a valid place.
Step 4 · Add the layer cache and the build attestations
Two more groups of inputs make the build faster and more trustworthy. Rewrite the build step with them, replacing the whole file so it stays exact:
cat > .github/workflows/image.yml <<'YAML'
name: Container image
on:
push:
branches: [main]
tags: ['v*.*.*']
pull_request:
branches: [main]
permissions:
contents: read
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v7
- name: Set up QEMU for arm64 builds
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Work out tags and labels
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=edge,branch=main
type=sha
type=ref,event=pr
- name: Build, and push outside pull requests
id: build
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
annotations: ${{ steps.meta.outputs.annotations }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: mode=max
sbom: true
YAMLThe cache lines:
type=ghastores BuildKit's layer cache in the same GitHub Actions cache thatactions/cacheuses, so the same rules apply: a run reads caches from its own branch, its base branch and the default branch, and the repository shares one storage limit.mode=maxsaves the layers of every build stage, not only the final image. It matters once your Dockerfile has a build stage that installs dev dependencies; withmin, those layers are rebuilt every time.- If one repository builds several images, give each one its own
scope=(for exampletype=gha,scope=api) on both lines, or each build overwrites the last one's cache.
The attestation lines:
provenance: mode=maxattaches a record, written by BuildKit, of how the image was built: the repository, commit, workflow and build arguments. Without the line, the action already adds provenance, atmaxfor public repositories andminfor private ones; setting it states your choice.- Because build arguments appear in that record, never pass a token or password with
build-args. Use build secrets for anything private. sbom: trueattaches a software bill of materials, a list of the packages inside the image, which scanners can read without unpacking it.
Both are stored in the registry next to the image, not inside its layers, so they do not make the image any larger to pull.
Check it worked
actionlint .github/workflows/image.yml
grep -n -E 'cache-(from|to)|provenance|sbom' .github/workflows/image.ymlactionlint prints nothing, and grep shows four lines: cache-from: type=gha, cache-to: type=gha,mode=max, provenance: mode=max and sbom: true.
Step 5 · Pass the image to the next job by digest
A tag is a name that can be moved. edge points at a new image after every merge, and anyone with push rights can retag 1.4.2. A digest, sha256: followed by 64 hex characters, is a hash of the image itself, so ghcr.io/acme/ghcr-demo@sha256:… always means the same bytes. Deploy by digest and a rollback means redeploying a known digest, not hoping a tag has not changed.
build-push-action returns the digest as the digest output of the step. For a multi-platform build it is the digest of the image index, the small list that points to the amd64 and arm64 images; the server pulling it receives the one that matches its processor. Expose it as a job output and use it in a second job. Rewrite the file once more:
cat > .github/workflows/image.yml <<'YAML'
name: Container image
on:
push:
branches: [main]
tags: ['v*.*.*']
pull_request:
branches: [main]
permissions:
contents: read
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
outputs:
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: actions/checkout@v7
- name: Set up QEMU for arm64 builds
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Work out tags and labels
id: meta
uses: docker/metadata-action@v6
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=edge,branch=main
type=sha
type=ref,event=pr
- name: Build, and push outside pull requests
id: build
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
annotations: ${{ steps.meta.outputs.annotations }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: mode=max
sbom: true
deploy:
needs: image
if: github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- name: Pin the image by digest
env:
DIGEST: ${{ needs.image.outputs.digest }}
run: |
IMAGE="${REGISTRY}/${GITHUB_REPOSITORY,,}@${DIGEST}"
echo "Deploying ${IMAGE}"
echo "Pinned image: \`${IMAGE}\`" >> "$GITHUB_STEP_SUMMARY"
YAMLPoints to notice:
- The
deployjob runs only onpushevents, so pull requests never reach it. It has nopackages: write; it inherits the read-only default. - The digest reaches the shell through
env, not by pasting${{ … }}into the script. That habit keeps values from outside the script from being run as shell code. ${GITHUB_REPOSITORY,,}is bash for "lowercase this", because a repository calledAcme/GHCR-Demomust be writtenacme/ghcr-demoin an image reference.- Replace the two
echolines with your real deploy, using${IMAGE}wherever you would have written a tag: in a Compose file, a Kubernetes manifest or an SSH command. The SSH deploy tutorial linked at the end shows one way.
Check it worked
actionlint .github/workflows/image.yml
echo "actionlint exit code: $?"Exit code 0. Then make the kind of typo that would otherwise give the deploy job an empty digest and an image reference ending in @:
sed 's/needs\.image\.outputs\.digest/needs.image.outputs.digets/' .github/workflows/image.yml > /tmp/image-typo.yml
if actionlint /tmp/image-typo.yml; then
echo "expected actionlint to report the typo"; false
else
echo "actionlint caught the wrong output name"
fi
rm /tmp/image-typo.ymlactionlint names digets as a property that is not defined, with its line and column, and the last line reads actionlint caught the wrong output name.
Step 6 · Push, tag a release and inspect what arrived
Connect the folder to the empty repository you created at the start. Replace <your-user> and <your-repo> with your GitHub user or organisation and the repository name (use the HTTPS address instead if you do not push over SSH):
git remote add origin git@github.com:<your-user>/<your-repo>.gitCommit the files and push to main in that repository; git init -b main in the first step already named the branch main, which the workflow's triggers expect:
git add Dockerfile .dockerignore package.json server.js .github/workflows/image.yml
git commit -m "Build and push the container image from Actions"
git push origin mainThe first run takes several minutes: the arm64 half of the build runs under emulation, and the cache starts empty. A second push with no Dockerfile change is much faster, because every layer comes from the cache. If the run fails at the push with denied or permission_denied, check that a package with the same name does not already exist from an earlier manual push; connect it to the repository in the package's settings on GitHub, or delete it, and run the workflow again.
When it is green, cut a release:
git tag v1.0.0
git push origin v1.0.0Check it worked
Open the run of the tag push on GitHub. The deploy job's summary shows a line like Pinned image: ghcr.io/acme/ghcr-demo@sha256:…. Your repository's front page now lists the package under Packages, with the tags 1.0.0, 1.0, latest and a sha- tag; edge came from the push to main.
On your own machine, with Docker installed, inspect the release (replace acme/ghcr-demo with your lowercase owner and repository). A private image needs docker login ghcr.io first, with a personal access token that has read:packages, entered at the prompt:
docker buildx imagetools inspect ghcr.io/acme/ghcr-demo:1.0.0The output lists the index digest, which matches the one in the job summary, and a manifest for linux/amd64 and one for linux/arm64, plus unknown/unknown entries that hold the provenance and SBOM. Then run the image by digest, pasting the digest from the summary:
docker run --rm -p 3000:3000 ghcr.io/acme/ghcr-demo@sha256:<digest>In another terminal, curl http://localhost:3000 prints ghcr-demo running on x64 on an Intel or AMD machine, or on arm64 on Apple silicon or an arm64 server. Docker downloads only the platform that matches, which helps on a metered or prepaid connection; pulling by the same digest again downloads nothing.
To remove the demo from your machine afterwards:
rm -rf ~/ghcr-demo
rm -f ~/.local/bin/actionlint ~/.local/bin/hadolintDelete the test package on GitHub from the package's settings page if you published it only to try this.
Next steps
- Make the image smaller before you build it for two platforms: /tutorials/make-docker-images-smaller-multi-stage
- Write a production Dockerfile with dependencies for the same kind of service: /tutorials/write-a-dockerfile-for-a-node-app
- Deploy the pinned image to a server from the
deployjob: /tutorials/deploy-to-a-server-over-ssh-with-github-actions - See how the GitHub Actions cache decides what a branch can read: /tutorials/cache-dependencies-and-build-outputs-in-github-actions
Related tutorials
- Run only the CI jobs a change needs with path filters and concurrencyYou will have GitHub Actions workflows that skip tests for documentation-only changes without blocking merges, cancel superseded pull request runs, queue deploys instead of cancelling them, and stop any job that runs too long.
- Run Python tests and linters in GitHub Actions with uvYou will have a GitHub Actions workflow that installs a Python project with uv from its lock file, fails on a stale uv.lock, runs Ruff and pytest with a coverage floor on two Python versions, caches uv's downloads and keeps the coverage report as an artifact.
- Publish an npm package from GitHub Actions with trusted publishing and provenanceYou will have a small npm package that GitHub Actions publishes on each version tag through npm trusted publishing, with no NPM_TOKEN secret and a provenance attestation on every release.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials