DEV Community

Cover image for Auto-Tag Docker Images with Semantic Versioning Using GitHub Actions
Amol Mali
Amol Mali

Posted on

Auto-Tag Docker Images with Semantic Versioning Using GitHub Actions

🚀 Auto-Tag Docker Images with Semantic Versioning Using GitHub Actions

Docker images tagged with long SHA hashes are hard to track. Let's fix that.

In this guide, you’ll learn how to automatically build and push Docker images to Docker Hub using semantic version tags like v1.0.0, and optionally update latest as well — all triggered directly by a git tag.


🧰 Prerequisites

Before getting started, make sure you have:

  • A working GitHub repository with a Dockerfile
  • A Docker Hub account
  • GitHub Secrets:
    • DOCKER_USERNAME
    • DOCKER_PASSWORD or access token
  • Semantic version tags in your repository (e.g., git tag v1.2.3)

🔄 What We'll Automate

  • Watch for pushes to tags like v1.2.3
  • Extract the tag version from GITHUB_REF
  • Build the Docker image
  • Tag it with both v1.2.3 and latest
  • Push both to Docker Hub

⚙️ GitHub Actions Workflow

Here's a complete example of a workflow file to place at .github/workflows/docker-release.yml:


yaml
name: Release Docker Image

on:
  push:
    tags:
      - 'v*.*.*'  # Matches v1.0.0, v2.3.1 etc.

jobs:
  docker:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3

      - name: Extract tag version
        id: version
        run: echo "VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV

      - name: Log in to Docker Hub
        run: echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin

      - name: Build Docker image
        run: |
          docker build -t ${{ secrets.DOCKER_USERNAME }}/your-app:${{ env.VERSION }} .
          docker tag ${{ secrets.DOCKER_USERNAME }}/your-app:${{ env.VERSION }} ${{ secrets.DOCKER_USERNAME }}/your-app:latest

      - name: Push Docker image
        run: |
          docker push ${{ secrets.DOCKER_USERNAME }}/your-app:${{ env.VERSION }}
          docker push ${{ secrets.DOCKER_USERNAME }}/your-app:latest
Enter fullscreen mode Exit fullscreen mode

Top comments (0)