DEV Community

Cover image for Host Docker Image Builds with GitHub
JohnDotOwl
JohnDotOwl

Posted on

Host Docker Image Builds with GitHub

Docker has become an essential tool for developing and deploying applications. Pairing Docker with GitHub workflows allows you to easily build Docker images and push them to registries like GitHub Container Registry (GHCR) on every code change. In this post, I'll show you how to set up a GitHub workflow to build and publish a Docker image.

The Sample Project

For this example, let's say we have a simple Node.js application called project-name that we want to Dockerize. The source code is hosted in a GitHub repo.

Our goal is to build a Docker image and push it to GHCR every time code is pushed to GitHub. This will allow us to always have an up-to-date Docker image built from the latest source.

Creating the GitHub Workflow

GitHub workflows are defined in YAML files stored in the .github/workflows directory of your repo. Let's create a file called docker-image.yml with the following contents:

name: Docker Image CI for GHCR

on: push

jobs:
  build_and_publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: build and push the image
        run: |
          docker login --username username --password ${{secrets.GITHUB_TOKEN}} ghcr.io
          docker build . --tag ghcr.io/username/project-name:latest
          docker push ghcr.io/username/project-name:latest

Enter fullscreen mode Exit fullscreen mode

This defines a workflow that will run on every push to GitHub. It has one job called build_and_publish that will build the Docker image and push it to GHCR.

The steps use the GitHub Actions checkout action to clone the repo code. Then we build the image, tag it with the GHCR repository path, and push it.

The GITHUB_TOKEN secret allows us to authenticate with GHCR.

Triggering the Workflow

With the workflow defined, we can now trigger it by pushing code to GitHub.

For example, if we make a small change and push it:

git commit -m "Update README"
git push origin main
Enter fullscreen mode Exit fullscreen mode

This will trigger the workflow, build the image, and push it to your GHCR repo.

We now have automated Docker image builds on every code change! The same pattern can be used to build and publish images to Docker Hub or other registries.

GitHub workflows are powerful for automating all kinds of development tasks. For Docker specifically, they provide an easy way to implement continuous integration and deployment pipelines.

Abstract

This post shows one of the most minimal GitHub workflows for automated Docker image builds on code pushes. The straightforward YAML provides a great example of no-frills Docker CI/CD.

Top comments (0)