GitHub Actions — Docker Build and Publish
Build multi-platform Docker images and push to GitHub Container Registry with caching and tagging.
name: Build and Push Docker Image
on:
push:
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:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GHCR
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.IMAGE_NAME }}
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
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
cache-to: type=gha,mode=maxSponsored
DigitalOcean
Use Cases
- Publishing Docker images on release tags
- Multi-platform image builds for ARM and x86
- Container registry integration with GitHub releases
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
GitHub Actions Docker Build and Push
GitHub Actions workflow to build a Docker image and push it to GitHub Container Registry on release.
Best for: Automated Docker image publishing on release
GitHub Actions CI/CD Pipeline
Complete GitHub Actions workflow with test, build, and deploy stages for a Node.js application.
Best for: Automated testing and deployment on push
GitHub Actions Test Matrix Strategy
GitHub Actions workflow with matrix strategy to test across multiple Node versions and OS platforms.
Best for: Cross-platform compatibility testing
GitHub Actions — Node.js CI Pipeline
Complete CI workflow for Node.js: install, lint, test, build on every push and PR with caching.
Best for: Automated testing on every push and PR