infoalloggi-monorepo/build_and_push_ghcr.sh

73 lines
2.2 KiB
Bash
Raw Normal View History

#!/usr/bin/env bash
set -euo pipefail
# Build and push multiple Docker images to a registry (GHCR or self-hosted)
# Usage:
# ./build_and_push_ghcr.sh [TAG]
# Environment variables (defaults shown):
# TAG (arg or env, default: latest)
# IMAGE_REGISTRY (default: ghcr.io)
# OWNER (default: marcopedone)
# SERVICES (space-separated list, default: backend web db)
# USERNAME (optional): registry username for docker login
# TOKEN (optional): registry password/token for docker login
#
# The script expects subfolders for services when building from source:
# - db -> ./apps/db
# - backend -> ./apps/backend
# - web -> ./apps/infoalloggi
: "${TAG:?TAG is required}"
: "${IMAGE_REGISTRY:?IMAGE_REGISTRY is required}"
2025-10-23 15:16:42 +02:00
: "${PREFIX:?PREFIX is required}"
: "${OWNER:?OWNER is required}"
: "${SERVICES:?SERVICES is required}"
: "${USERNAME:?USERNAME is required}"
: "${TOKEN:?TOKEN is required}"
: "${ENV_FILE:?ENV_FILE is required}"
set -x
# Optional login
if [[ -n "${USERNAME}" && -n "${TOKEN}" ]]; then
echo "Logging into ${IMAGE_REGISTRY} as ${USERNAME}..."
echo "${TOKEN}" | docker login "${IMAGE_REGISTRY}" -u "${USERNAME}" --password-stdin
else
echo "No credentials provided; assuming you're already logged into ${IMAGE_REGISTRY} or using a credential helper."
fi
for svc in ${SERVICES}; do
case "${svc}" in
db)
ctx="./apps/db"
dockerfile="Dockerfile"
;;
backend)
ctx="./apps/backend"
dockerfile="Dockerfile"
;;
web)
ctx="./apps/infoalloggi"
dockerfile="Dockerfile"
;;
*)
echo "Unknown service: ${svc}, skipping..."
continue
;;
esac
# Get last git commit info
GIT_COMMIT_ID=$(git rev-parse --short HEAD)
GIT_COMMIT_MSG=$(git log -1 --pretty=%B | tr -d '\n')
DESCRIPTION="Commit: ${GIT_COMMIT_ID} - ${GIT_COMMIT_MSG}"
2025-10-23 15:16:42 +02:00
IMAGE="${IMAGE_REGISTRY}/${OWNER}/${PREFIX}-${svc}:${TAG}"
echo "Building ${PREFIX}-${svc} -> ${IMAGE} (context: ${ctx})"
docker build --build-arg ENV_FILE="${ENV_FILE}" -t "${IMAGE}" --label "org.opencontainers.image.description=${DESCRIPTION}" -f "$ctx/$dockerfile" "$ctx"
echo "Pushing ${IMAGE}"
docker push "${IMAGE}"
done
2025-10-23 15:16:42 +02:00
echo "All done. Built and pushed services: ${SERVICES} with tag ${TAG} to ${IMAGE_REGISTRY}/${OWNER}/${PREFIX}-<service>:${TAG}"