Building and pushing a Docker image
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's tests pass on main, but a green check is not something a server can run. The pipeline must also build the Docker image and publish it, tagged so you always know which commit it came from.
Buildx and logging in to ghcr.io
GHCR (GitHub Container Registry) is GitHub's registry for Docker images, at ghcr.io. Images live under your user or organisation, for example ghcr.io/asha-rao/shoplite-api.
The image job first logs in to the registry and asks for the right to push. These are its first steps.
image: runs-on: ubuntu-latest permissions: contents: read packages: write # allow GITHUB_TOKEN to push to ghcr.io steps: - uses: actions/checkout@v5 - uses: docker/setup-buildx-action@v3 - uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }}docker/setup-buildx-action prepares Buildx, Docker's modern builder, which the push and cache features need. docker/login-action logs the runner in to the registry. For GHCR you need no personal password: every run gets an automatic GITHUB_TOKEN, a short-lived token for this repository.
Its rights are set with permissions:. Pushing images needs packages: write, and checking out needs contents: read. Give these on the image job only, so other jobs keep the smallest rights.
Fix the error
Fix the permission error
Choose the line that replaces the wrong one.
The push fails. Which line replaces line 5?
Error
denied: permission_denied: write_package
docker/metadata-action: tags from SHA, branch and git tags
A SHA tag is an image tag made from the commit SHA, such as sha-4e1c9a7. It points to one commit forever, unlike main or latest, which move with every push.
This program mimics the tag rules for two events: a push to main and a release tag v1.2.0.
Example 1 · Which tags does metadata-action produce?
import java.util.ArrayList;import java.util.List;
public class ImageTagsDemo { static final String IMAGE = "ghcr.io/asha-rao/shoplite-api";
// Rules: type=sha, type=ref,event=branch, type=semver {{version}} and {{major}}.{{minor}} static List<String> tags(String ref, String sha) { List<String> tags = new ArrayList<>(); if (ref.startsWith("refs/heads/")) { tags.add(ref.substring("refs/heads/".length())); } else if (ref.startsWith("refs/tags/v")) { String version = ref.substring("refs/tags/v".length()); tags.add(version); tags.add(version.substring(0, version.lastIndexOf('.'))); } tags.add("sha-" + sha.substring(0, 7)); return tags; }
public static void main(String[] args) { String sha = "4e1c9a7d0b2f63a8c5e94d1f07a2b6c3e8d9f012"; for (String ref : new String[] {"refs/heads/main", "refs/tags/v1.2.0"}) { System.out.println(ref + ":"); for (String tag : tags(ref, sha)) { System.out.println(" " + IMAGE + ":" + tag); } } }}refs/heads/main: ghcr.io/asha-rao/shoplite-api:main ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7 refs/tags/v1.2.0: ghcr.io/asha-rao/shoplite-api:1.2.0 ghcr.io/asha-rao/shoplite-api:1.2 ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7
What this code does
- A push to main gives a moving
maintag and a fixedsha-tag; a release tagv1.2.0gives version tags without thev. This is a small model of the action's rules, not its code. - The same commit gets the same
sha-4e1c9a7tag in both cases, so you can always trace any tag back to one commit.
docker/metadata-action works out the image tags and labels from the event, so you do not build tag strings by hand. Common tag rules:
type=sha:sha-plus the short commit SHA.type=ref,event=branch: the branch name, such asmain.type=semver,pattern={{version}}: for a git tagv1.2.0, the tag1.2.0.
With a SHA tag, "production runs sha-4e1c9a7" tells you the exact code, and rolling back means redeploying the previous SHA. The action also adds standard labels, such as the source repository, which link the package to your repository on GitHub.
Predict the output
What is running?
Think about which tags move and which stay.
Round 1 of 3
A bug appears. What does the tag latest tell you about the running code?
docker/build-push-action: push only from main
docker/build-push-action builds the image with Buildx and, when push is true, pushes every tag from the metadata step to the registry.
This is the whole image job. It builds on every run, but a condition makes it push only after a push to main.
Example 2 · .github/workflows/ci.yml: the image job
Runs in: a GitHub repository with the shoplite-api project and its Dockerfile
image: needs: build-test # only after the tests passed runs-on: ubuntu-latest permissions: contents: read packages: write steps: - uses: actions/checkout@v5 - uses: docker/setup-buildx-action@v3 - name: Log in to GHCR if: github.event_name == 'push' && github.ref == 'refs/heads/main' uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Image tags and labels id: meta uses: docker/metadata-action@v5 with: images: ghcr.io/${{ github.repository_owner }}/shoplite-api tags: | type=sha type=ref,event=branch type=semver,pattern={{version}} - name: Build, and push on main uses: docker/build-push-action@v6 with: context: . push: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} cache-from: type=gha cache-to: type=gha,mode=max(push to main) Run docker/login-action@v3 Login Succeeded! Run docker/metadata-action@v5 Docker tags: ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7 ghcr.io/asha-rao/shoplite-api:main Run docker/build-push-action@v6 #14 exporting to image #14 pushing layers 4.1s done #14 pushing manifest for ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7@sha256:9c1f2e... #14 DONE 6.8s (pull request #42) Log in to GHCR skipped Run docker/build-push-action@v6 #14 exporting to image #14 DONE 0.9s (built, not pushed)
What this code does
needs: build-testmeans no image is built from red code; the expression inpush:evaluates totrueonly for a push to main, so pull requests build the image (catching Dockerfile errors) but never publish it.steps.meta.outputs.tagspasses the computed tags to the build step; the login is skipped on pull requests because nothing is pushed there.
Build on every pull request, so a broken Dockerfile is caught before merge, but push only from main: unmerged code must never become a published image.
The job runs needs: build-test, so no image is built from red code, and the type=gha layer cache from the caching lesson keeps it fast.
Find the bug
Spot the unsafe push
Tap the line that is wrong.
Images from unmerged pull requests appear in the registry. Which line is the problem?
Round 1 of 2Secrets, variables and environments
A secret is an encrypted value stored in the repository settings, such as a deploy token. A workflow reads it as ${{ secrets.NAME }}, and GitHub hides its exact value in logs as ***.
GitHub masks a secret in logs, but only its exact value. This program shows how a changed form slips through.
Example 3 · Why printing a secret is never safe
import java.util.Base64;import java.util.List;
public class SecretMaskDemo { static final String SECRET = "pay_test_51HxQ8";
// Like GitHub: replace the exact secret value in every log line static String mask(String logLine) { return logLine.replace(SECRET, "***"); }
public static void main(String[] args) { List<String> lines = List.of( "key is " + SECRET, "key length: " + SECRET.length(), "key base64: " + Base64.getEncoder().encodeToString(SECRET.getBytes()), "key reversed: " + new StringBuilder(SECRET).reverse()); lines.forEach(l -> System.out.println(mask(l))); }}key is *** key length: 15 key base64: cGF5X3Rlc3RfNTFIeFE4 key reversed: 8QxH15_tset_yap
What this code does
- Masking only finds the exact value. Its base64 or reversed form passes straight through, and anyone who can read the log can turn it back.
- Printing the length is the safe way to check a secret is set; better still, use
if: env.MY_SECRET != ''and never echo it at all.
GitHub stores three kinds of settings for workflows (repository Settings → Secrets and variables → Actions). Besides secrets:
- Variables (
${{ vars.NAME }}): plain, non-secret settings such as an image name or region, visible in logs. - Environments (such as
production): named targets with their own secrets, variables and protection rules like a required reviewer. A job opts in withenvironment: production.
Never print a secret, not even "to check it". If one leaks, rotate it: create a new value and delete the old one.
Predict the output
Does the secret leak?
Masking replaces the exact secret with ***.
Round 1 of 2
Which line still shows the secret to anyone who reads the log?
Pulling the pushed image to prove it works
A private package is a GHCR image that only you and the people you share it with can pull. New packages are private by default; pulling one needs docker login with a token that has read:packages.
A pushed image is only useful if it runs. These commands pull the SHA-tagged image and start it, as a server would.
Example 4 · Pull the pushed image and run it
Runs in: a terminal with Docker 27+ and the ShopLite Compose database running
# private package: log in once with a token that has read:packagesecho "$GHCR_TOKEN" | docker login ghcr.io -u asha-rao --password-stdindocker pull ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7docker run --rm -d --name shoplite-ci-check -p 8080:8080 \ --network shoplite_default \ -e DB_URL=jdbc:mysql://db:3306/shoplite -e DB_USER=shoplite \ -e DB_PASSWORD="$MYSQL_PASSWORD" -e JWT_SECRET="$JWT_SECRET" \ ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7curl -s http://localhost:8080/actuator/healthLogin Succeeded
sha-4e1c9a7: Pulling from asha-rao/shoplite-api
...
Digest: sha256:9c1f2e0b7a4d...
Status: Downloaded newer image for ghcr.io/asha-rao/shoplite-api:sha-4e1c9a7
6b0e3c1f9d2a...
{"status":"UP"}What this code does
- The container joins the Compose project's network, so it finds MySQL at
db:3306; stop the Composeapiservice first if it already uses port 8080.--password-stdinkeeps the token out of your shell history. - Health UP from the exact SHA-tagged image proves the pipeline publishes working releases; this is what a deploy will do in the next module.
After the first push, open your GitHub profile's Packages tab: shoplite-api appears with its tags. Either make it public in the package settings or log in with a personal access token.
Then pull the SHA tag and run it against the Compose database. If the health check is UP, the image the pipeline built is a working release.
Next step
Check your understanding
12 quick questions