Skip to content

Docker Build and Push #3

Docker Build and Push

Docker Build and Push #3

Workflow file for this run

name: Docker Build and Push
on:
workflow_dispatch:
inputs:
environment:
description: 'Environment to deploy to'
required: true
type: choice
options:
- dev
- staging
tag_suffix:
description: 'Additional tag suffix (optional)'
required: false
type: string
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build-and-push:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Generate tags
id: tags
run: |
BRANCH_NAME=${GITHUB_REF#refs/heads/}
SHA_SHORT=$(git rev-parse --short HEAD)
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
# Convert repository name to lowercase
REPO_NAME=$(echo "${{ github.repository }}" | tr '[:upper:]' '[:lower:]')
# Set default environment for push events
if [ "${{ github.event_name }}" = "push" ]; then
ENV="dev"
else
ENV="${{ github.event.inputs.environment }}"
fi
# Base tags
TAGS="${{ env.REGISTRY }}/${REPO_NAME}:${ENV}"
TAGS="${TAGS},${{ env.REGISTRY }}/${REPO_NAME}:${BRANCH_NAME}-${SHA_SHORT}"
TAGS="${TAGS},${{ env.REGISTRY }}/${REPO_NAME}:${BRANCH_NAME}-${ENV}"
# Add timestamp tag
TAGS="${TAGS},${{ env.REGISTRY }}/${REPO_NAME}:${BRANCH_NAME}-${TIMESTAMP}"
# Add custom suffix if provided (only for workflow_dispatch)
if [ "${{ github.event_name }}" = "workflow_dispatch" ] && [ -n "${{ github.event.inputs.tag_suffix }}" ]; then
TAGS="${TAGS},${{ env.REGISTRY }}/${REPO_NAME}:${ENV}-${{ github.event.inputs.tag_suffix }}"
fi
echo "tags=${TAGS}" >> $GITHUB_OUTPUT
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
file: Dockerfile.prod
push: true
tags: ${{ steps.tags.outputs.tags }}
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Print image tags
run: |
echo "Image was built and pushed with the following tags:"
echo "${{ steps.tags.outputs.tags }}" | tr ',' '\n'