Use GitHub action to publishing Docker image to Docker Hub repository

GitHub action

Each time you push the code or create a new release on GitHub, you can trigger a workflow to publish your image. The workflow in the example below runs when the push event triggers.

In the example workflow below, we use the Docker build-push-action action to build the Docker image and, if the build succeeds, push the built image to Docker Hub.

Prerequisites

  • Github Account

    GitHub is where over 56 million developers shape the future of software, together. Contribute to the open source community, manage your Git repositories, review code like a pro, track bugs and features, power your CI/CD and DevOps workflows, and secure code before you commit it.

  • Docker Hub Account

    To push to Docker Hub, you will need to have a Docker Hub account, and have a Docker Hub repository created. For more information, see “Pushing a Docker container image to Docker Hub” in the Docker documentation.

    The build-push-action options required for Docker Hub are:

    username and password: This is your Docker Hub username and password. We recommend storing your Docker Hub username and password as secrets so they aren’t exposed in your workflow file. For more information, see “Creating and using encrypted secrets.” Encrypted secrets - GitHub Docs - https://docs.github.com/en/actions/reference/encrypted-secrets.

    repository: Your Docker Hub repository in the format DOCKER-HUB-NAMESPACE/DOCKER-HUB-REPOSITORY.

Configuration

build-push-action options

Create the .github/workflows/publish.yml file.

Remember to replace cloudolife/col-github-action-example with your prefer Docker Hub repository.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# .github/workflows/publish.yml

name: Publish Docker image

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

jobs:
push_to_registry:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v2

- name: Push to Docker Hub
uses: docker/build-push-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
repository: cloudolife/col-github-action-example
tag_with_ref: true

GitHub action will run automatically after your push the code to GitHub.

References

[1] Publishing Docker images - GitHub Docs - https://docs.github.com/en/actions/guides/publishing-docker-images

[2] Repositories | Docker Documentation - https://docs.docker.com/docker-hub/repos/#pushing-a-docker-container-image-to-docker-hub

[3] Learn GitHub Actions - GitHub Docs - https://docs.github.com/en/actions/learn-github-actions

[4] Encrypted secrets - GitHub Docs - https://docs.github.com/en/actions/reference/encrypted-secrets

[5] Github - https://github.com/

[6] Docker Hub - https://hub.docker.com/