โWrite a job that, only on pushes to main, builds and pushes my image to ghcr.io/OWNER/REPO using the built-in GITHUB_TOKEN, tagged latest and the commit SHA.โ
06 โ Push your image to GHCR from Actions
Category: Docker in CI ยท Priority: High ยท Step: 7
Turn CI into CD: on a push to
main, build and publish the image to GitHub Container Registry.
๐ฏ What is this task?
Now you publish the image automatically. Using the built-in GITHUB_TOKEN, the workflow logs in to GHCR (ghcr.io) and pushes a tagged image โ no manual docker push ever again. This is your first taste of Continuous Delivery.
๐ Builds on: Project 1, lesson 11 (Push to GHCR) โ same registry, now automated.
๐ค AI Prompt
"Write a GitHub Actions job that, only on pushes to main, builds my Docker image and pushes it to ghcr.io/OWNER/REPO using the built-in GITHUB_TOKEN. Tag it with both
latestand the commit SHA."
๐ Step-by-step
publish:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: |
ghcr.io/${{ github.repository }}:latest
ghcr.io/${{ github.repository }}:${{ github.sha }}
if: github.ref == 'refs/heads/main'โ only publish frommain, not from feature branches or PRs.permissions: packages: writeโ letsGITHUB_TOKENpush to GHCR.- Tagging with
${{ github.sha }}gives every build a unique, traceable tag.
โ Done when
- A push to
mainpublishes an image toghcr.io/<owner>/<repo> - The package appears under your repo's Packages
- Feature branches build but do not publish
๐ Quiz
Answer all 3 questions correctly to complete this lesson.