Skip to content

Docker build and push API service to ghcr.io #77

Docker build and push API service to ghcr.io

Docker build and push API service to ghcr.io #77

name: "Docker build and push API service to ghcr.io"
on:
schedule: # Scheduled workflows only run on the default branch
- cron: '0 3 * * *' # Nightly at 3 AM UTC
push:
branches:
- main
pull_request:
branches:
- main
workflow_dispatch:
env:
SERVICE: api
REGISTRY: ghcr.io
REPO: ${{ github.repository }}
REPO_OWNER: ${{ github.repository_owner }}
EVENT: ${{ github.event_name }}
jobs:
build-and-push:
name: "Docker build and push API service to ghcr.io"
runs-on: ubuntu-latest
permissions:
contents: read
packages: write # Needed to push to GHCR
steps:
- name: Set ENV vars
run: |
# remove owner from repo URI, e.g. "owner/repo_name", to get repo name
echo "REPO_NAME=${REPO#$REPO_OWNER/}" >> "$GITHUB_ENV"
# determine tag based on type of GH event
if [[ "$EVENT" == "schedule" ]]; then
echo "TAG=nightly" >> "$GITHUB_ENV"
elif [[ "$EVENT" == "push" ]]; then
echo "TAG=latest" >> "$GITHUB_ENV"
elif [[ "$EVENT" == "pull_request" ]]; then
echo "TAG=pr-${{ github.event.pull_request.number }}" >> "$GITHUB_ENV"
else
echo "TAG=unknown" >> "$GITHUB_ENV"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Build and start container (as backing service)
run: |
docker compose up --build --detach $SERVICE
- name: Wait for container to be ready
run: |
RETRIES=10
for i in `seq 1 $RETRIES`; do
echo "Checking health... attempt $i"
status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/health || true)
if [ "$status" == "200" ]; then
echo "✅ Health check passed!"
exit 0
fi
sleep 5
done
echo "❌ Health check failed after $RETRIES retries."
docker compose logs
exit 1
- name: Log in to GHCR
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Tag and push image
run: |
# make sure all values are lowercase for repository image name
registry="$(echo $REGISTRY | tr '[:upper:]' '[:lower:]')"
repo_owner="$(echo $REPO_OWNER | tr '[:upper:]' '[:lower:]')"
repo_name="$(echo $REPO_NAME | tr '[:upper:]' '[:lower:]')"
service="$(echo $SERVICE | tr '[:upper:]' '[:lower:]')"
tag="$(echo $TAG | tr '[:upper:]' '[:lower:]')"
image_name="$repo_name-$service"
source_image="$image_name:latest"
target_image="$registry/$repo_owner/$image_name:$tag"
echo "source_image: $source_image"
echo "target_image: $target_image"
docker tag $source_image $target_image
docker push $target_image
- name: Clean up
run: docker compose down