docker-build.yml•2.96 kB
name: Build and Publish Docker Image
on:
push:
branches:
- main
tags:
- 'v*'
pull_request:
branches:
- main
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v5
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
if: github.event_name != 'pull_request'
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
# Tag with version on release tags (v1.0.0 -> 1.0.0)
type=semver,pattern={{version}}
# Tag with major.minor on release tags (v1.0.0 -> 1.0)
type=semver,pattern={{major}}.{{minor}}
# Tag with major on release tags (v1.0.0 -> 1)
type=semver,pattern={{major}}
# Tag with 'latest' on main branch
type=raw,value=latest,enable={{is_default_branch}}
# Tag with branch name
type=ref,event=branch
# Tag with PR number for PRs
type=ref,event=pr
# Tag with commit SHA (short form)
type=sha,format=short
- name: Build Docker image
uses: docker/build-push-action@v6
with:
context: .
push: false
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
load: true
- name: Test Docker image
run: |
# Run a basic test to ensure the image starts correctly
docker run --rm ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }} --version || echo "Version check not available"
- name: Push Docker image to registry
if: startsWith(github.ref, 'refs/tags/v')
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Image published
if: startsWith(github.ref, 'refs/tags/v')
run: |
echo "✅ Docker image published to ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}"
echo "📦 Tags: ${{ steps.meta.outputs.tags }}"
echo ""
echo "To use this image:"
echo " docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.meta.outputs.version }}"