GitHub Actions: Push to Docker on Multiple Events

March 12, 2022
Build and push Docker image on multiple GitHub events, eg. on push and on new release.

How This Works

This GitHub action workflow will build and push your image to Docker Hub on the following events:

Setup

First you must create a Docker repository if you don't have one already.

After that, create a Docker token and save it to the GitHub repository secrets.

  1. Go to https://hub.docker.com/settings/security and create a new access token.
  2. Go to your GitHub repository > Settings > Secrets > Actions > New repository secret
  3. Add a secret for DOCKERHUB_USERNAME with your Docker username.
  4. Add a secret for DOCKERHUB_TOKEN with the token from Docker.

Workflow

Copy paste this into your repository as .github/workflows/docker-image.yml

Remember to edit the name/app to match your Docker repository name.

name: Docker Build and Push

on:
  push:
    branches:
      - 'master'
  release:
    types: [published]

jobs:
  docker:
    runs-on: ubuntu-latest
    steps:
      -
        name: Checkout
        uses: actions/checkout@v2
      -
        name: Set up QEMU
        uses: docker/setup-qemu-action@v1
      -
        name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v1
      -
        name: Login to DockerHub
        uses: docker/login-action@v1
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      -
        # Push to master branch - push "latest" tag
        name: Build and Push (latest)
        if: github.event_name == 'push'
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          tags: name/app:latest
      -
        # Push the new release
        name: Build and Push New Release
        if: github.event_name == 'release'
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          tags: name/app:${{ github.event.release.tag_name }}

As you commit and push this file, the workflow should begin automatically - see the Actions tab in your GitHub repository.

You can learn more about this at https://github.com/marketplace/actions/build-and-push-docker-images

Follow RSS/Atom Feed
See more posts