Skip to content

Build and Push Docker Image #7

Build and Push Docker Image

Build and Push Docker Image #7

name: Build and Push Docker Image
on:
release:
types: [published]
workflow_dispatch:
inputs:
version:
description: 'Version tag for the Docker image'
required: true
default: 'latest'
jobs:
build-and-push:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry (GHCR)
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GHCR_PAT || secrets.GITHUB_TOKEN }}
- name: Log in to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_AT }}
- name: Determine version
id: use_version
run: |
# If the workflow is triggered by a release, use the release tag
if [ "${GITHUB_EVENT_NAME}" == "release" ]; then
VERSION="${GITHUB_REF#refs/tags/}"
else
VERSION="${{ github.event.inputs.version }}"
fi
VERSION_LOWER=$(echo $VERSION | tr '[:upper:]' '[:lower:]')
REPO_NAME=$(echo ${{ github.repository }} | tr '[:upper:]' '[:lower:]') # Use full lowercase repo name for both GHCR and DockerHub
echo "VERSION=$VERSION_LOWER" >> $GITHUB_ENV
echo "REPO_NAME=$REPO_NAME" >> $GITHUB_ENV
- name: Retrieve previous release version
id: previous_version
run: |
PREV_VERSION=$(gh release list --limit 2 --json tagName --jq '.[1].tagName' || echo "")
if [ -z "$PREV_VERSION" ]; then
echo "No previous version found, skipping retagging."
echo "PREV_VERSION=" >> $GITHUB_ENV
else
echo "Previous version: $PREV_VERSION"
echo "PREV_VERSION=$PREV_VERSION" >> $GITHUB_ENV
fi
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Build and Push Docker Image (GitHub Packages)
run: |
docker buildx build --platform linux/amd64,linux/arm64 \
--tag ghcr.io/${{ env.REPO_NAME }}:${{ env.VERSION }} \
--tag ghcr.io/${{ env.REPO_NAME }}:latest \
--push .
- name: Build and Push Docker Image (DockerHub)
run: |
docker buildx build --platform linux/amd64,linux/arm64 \
--tag ${{ env.REPO_NAME }}:${{ env.VERSION }} \
--tag ${{ env.REPO_NAME }}:latest \
--push .
- name: Retag and Push Previous Version (DockerHub)
if: env.PREV_VERSION != ''
run: |
docker pull ${{ env.REPO_NAME }}:latest
docker tag ${{ env.REPO_NAME }}:latest \
${{ env.REPO_NAME }}:${{ env.PREV_VERSION }}
docker push ${{ env.REPO_NAME }}:${{ env.PREV_VERSION }}