Building and Publishing Docker with GitHub Actions

In this post I am sharing my recipe for building and publishing Docker using GitHub Actions. It concisely wraps up a few steps that beginners often find problematic. In particular:

  • use GitHub secrets to securely store credentials, such as $DOCKER_USER and $DOCKER_PASSWORD, for your docker registry (such as DockerHub or GitHub Container Registry)
  • I recommend logging to the docker registry via the CLI, rather than using a less transparent GitHub Action, which is as simple as docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
  • use the correct tag pattern when pushing your docker to a registry
    • DockerHub: $DOCKER_USER/$IMAGE_NAME:$IMAGE_VERSION
    • GitHub Container: ghcr.io/$GITHUB_USER/$IMAGE_NAME:$IMAGE_VERSION

The sample code is shown below. See it in action on production here and in this template.

name: docker-image

on:
  push:
    branches: [ "main" ]
    paths: ["Dockerfile",".github/workflows/docker-image.yaml"]
  workflow_dispatch:


jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    # Docker tags and credentials for DockerHub/GitHub Containers, customize!
    env:
      IMAGE_NAME: plantuml-docker
      IMAGE_VERSION: latest
      DOCKER_USER: ${{ secrets.DOCKER_USER }}
      DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
      GITHUB_TOKEN: ${{ secrets.PAT }}
      GITHUB_USER: ${{ github.actor }}
    steps:
    - uses: actions/checkout@v3
    - name: Build and tag the image
      run: |
        docker build . \
        --tag $DOCKER_USER/$IMAGE_NAME:$IMAGE_VERSION \
        --tag ghcr.io/$GITHUB_USER/$IMAGE_NAME:$IMAGE_VERSION
    - name: Publish to DockerHub
      if: env.DOCKER_PASSWORD != ''
      run: |
        docker login -u $DOCKER_USER -p $DOCKER_PASSWORD
        docker push $DOCKER_USER/$IMAGE_NAME:$IMAGE_VERSION
    - name: Publish to GitHub Container registry
      if: env.GITHUB_TOKEN != ''
      run: |
        docker login ghcr.io -u $GITHUB_USER -p $GITHUB_TOKEN 
        docker push ghcr.io/$GITHUB_USER/$IMAGE_NAME:$IMAGE_VERSION

Published by mskorski

Scientist, Consultant, Learning Enthusiast

Leave a comment

Your email address will not be published. Required fields are marked *