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.
This blog is proudly sponsored by Datsi - Your Personal Database | Visit Datsi.io and learn more
How This Works
This GitHub action workflow will build and push your image to Docker Hub on the following events:
- Each push to the master branch will build and push the docker image "latest" tag.
- Each published release, will build and push the docker image tagged with the git tag. When you release v1.2.3 for git tag
1.2.3
it will create a docker image tagged1.2.3
.
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.
- Go to https://hub.docker.com/settings/security and create a new access token.
- Go to your GitHub repository > Settings > Secrets > Actions > New repository secret
- Add a secret for
DOCKERHUB_USERNAME
with your Docker username. - 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