Deploy Docker Images to DockerHub using GitHub Actions

I use a GitHub Action workflow similar to the one below to build and push container images automatically to DockerHub. The workflow collects metadata about the Image such as the software version, image tag, description and other metadata, builds the image using buildx and uploads it to DockerHub. Do the following first:

  1. Login to DockerHub and generate a Personal Access Token.
  2. Add the token as a repository secret in your GitHub Repo.
  3. Create the workflow file below in a .github/workflows directory:
name: Create and Publish a Docker Image

on:
  push:
    branches: ["main"]

jobs:
  build-and-push-image:
    name: Push Docker image to Docker Hub
    runs-on: ubuntu-latest
    steps:
      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: yourusername/your_app
          tags: |
            type=sha
            # set latest tag for the default branch
            type=raw,value=latest

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ vars.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and Push
        uses: docker/build-push-action@v3
        with:
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

It goes without saying that you’ll want to replace yourusername/your_app with your own details.

The workflow above automatically builds, tags images with the commit SHA and pushes the images to DockerHub whenever a push is made to the main branch.