Auto-rebuild Docker images if base image changes using GitHub actions

1 minute read

Let’s say you have a rather static docker image which is based on another image which changes frequently. Now your image should be rebuilt on two occasions: if your content changes, but also if the image yours is based on changed. This can be done relatively simple using a GitHub actions cron schedule. You just have to create an actions workflow file in your repository.

Adjust to your needs accordingly, and probably one can optimize even more by templating this.

# FILE LOCATION IN REPOSITORY:
#
#   .github/workflows/auto-build-on-base-image-change.yml
#

name: Regular base image update check
on:
  schedule:
    - cron: "23 13 3 * *"
  workflow_dispatch:


jobs:

  build:
    runs-on: ubuntu-latest
    steps:

      # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
      - uses: actions/checkout@v2

      - name: Docker Image Update Checker
        id: baseupdatecheck
        uses: lucacome/docker-image-update-checker@v1.1.0
        with:
          base-image: library/golang:alpine
          image: flypenguin/homepage-builder # update for your image

      # only execute subsequent steps if an update is actually NEEDED.
      # unfortunately we need to add an if-condition to all steps now
      # because a clean exit can't be triggered within a job it seems
      # (a cancellation is NOT the same and triggers a failure email)
      # see also https://github.com/actions/runner/issues/662

      - name: Login to DockerHub
        uses: docker/login-action@v1
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
        if: steps.baseupdatecheck.outputs.needs-updating == 'true'

      - name: Build and push Docker images
        uses: docker/build-push-action@v2.6.1
        with:
          context: "${{ github.workspace }}"
          push: true
          tags: flypenguin/homepage-builder:latest # update for your image
        if: steps.baseupdatecheck.outputs.needs-updating == 'true'

This particular image is a builder image for Hugo sites. Hugo switched from git submodule based theme management to a Go module based theme & plugin management. So the my builder image needs Go installed now. The easiest way to do this is to base this image on the official golang image. Since installing Go on every build adds time and network traffic this seemd “uncool”, so auto-updating the base image it was.

Sources: