Skip to content

Build and Push Docker Image #4

Build and Push Docker Image

Build and Push Docker Image #4

name: Build and Push Docker Image (Branch-Aware Tags)
on:
push:
tags:
- '*'
workflow_dispatch: ~
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
id-token: write
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v2
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract version info (tag or branch fallback)
id: version
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
git fetch --tags
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
TAG_NAME=$(git describe --tags --abbrev=0 "$(git rev-list --tags --no-walk --branches=$BRANCH_NAME | head -n 1)" 2>/dev/null || true)
if [[ -z "$TAG_NAME" ]]; then
TAG_NAME="${BRANCH_NAME//\//-}" # sanitize: replace slashes with dashes
fi
else
TAG_NAME="${GITHUB_REF#refs/tags/}"
fi
MAJOR_MINOR=$(echo "$TAG_NAME" | cut -d. -f1,2)
echo "TAG=$TAG_NAME" >> $GITHUB_ENV
echo "MAJOR_MINOR=$MAJOR_MINOR" >> $GITHUB_ENV
- name: Normalize repository name (lowercase)
run: |
echo "REPO_LOWER=$(echo '${{ github.repository }}' | tr '[:upper:]' '[:lower:]')" >> $GITHUB_ENV
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: |
ghcr.io/${{ env.REPO_LOWER }}:${{ env.TAG }}
ghcr.io/${{ env.REPO_LOWER }}:${{ env.MAJOR_MINOR }}