Skip to content

first commit

first commit #1

name: Build and Push Containers
on:
push:
branches:
- main
paths:
- '*/Dockerfile'
- '*/Dockerfile.*'
- '.github/workflows/build-and-push.yaml'
pull_request:
branches:
- main
paths:
- '*/Dockerfile'
- '*/Dockerfile.*'
workflow_dispatch:
inputs:
container:
description: 'Container name to build (leave empty to build all changed)'
required: false
type: string
env:
REGISTRY: ghcr.io
REGISTRY_OWNER: ${{ github.repository_owner }}
jobs:
detect-changes:
runs-on: ubuntu-latest
outputs:
containers: ${{ steps.detect.outputs.containers }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 2
- name: Detect changed containers
id: detect
run: |
if [ -n "${{ inputs.container }}" ]; then
# Manual trigger with specific container
CONTAINERS='["${{ inputs.container }}"]'
else
# Find directories with changed Dockerfiles
CHANGED=$(git diff --name-only HEAD~1 HEAD -- '*/Dockerfile' '*/Dockerfile.*' 2>/dev/null \
| awk -F'/' '{print $1}' \
| sort -u \
| jq -R . | jq -sc .)
if [ "$CHANGED" = "[]" ] || [ -z "$CHANGED" ]; then
# Fallback: build all containers (e.g. workflow file changed)
CONTAINERS=$(find . -maxdepth 2 -name 'Dockerfile' -o -name 'Dockerfile.*' \
| awk -F'/' '{print $2}' \
| sort -u \
| jq -R . | jq -sc .)
else
CONTAINERS="$CHANGED"
fi
fi
echo "containers=$CONTAINERS" >> "$GITHUB_OUTPUT"
echo "Will build: $CONTAINERS"
build-and-push:
runs-on: ubuntu-latest
needs: detect-changes
if: needs.detect-changes.outputs.containers != '[]'
permissions:
contents: read
packages: write
strategy:
matrix:
container: ${{ fromJson(needs.detect-changes.outputs.containers) }}
fail-fast: false
steps:
- name: Checkout
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
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
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.REGISTRY_OWNER }}/${{ matrix.container }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=sha-
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push
uses: docker/build-push-action@v6
with:
context: ${{ matrix.container }}
platforms: linux/amd64,linux/arm64
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.container }}
cache-to: type=gha,mode=max,scope=${{ matrix.container }}