Docker Build and Push to Registry
Build a Docker image and push it to Docker Hub or GitHub Container Registry using GitHub Actions. Covers multi-platform builds, tagging strategies, and login.
Detailed Explanation
Docker Build & Push with GitHub Actions
Building and pushing Docker images is one of the most common CI/CD tasks. This workflow uses the official Docker actions to build an image, tag it, and push it to a container registry.
Workflow YAML
name: Docker Build & Push
on:
push:
branches:
- main
tags:
- 'v*'
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: myuser/myapp
tags: |
type=ref,event=branch
type=semver,pattern={{version}}
type=sha
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
Key Components
- Docker Buildx: Enables advanced build features including multi-platform builds, build caching, and BuildKit optimizations.
- Login action: Authenticates with Docker Hub using repository secrets. For GitHub Container Registry (ghcr.io), use
registry: ghcr.iowith${{ secrets.GITHUB_TOKEN }}. - Metadata action: Automatically generates Docker tags based on Git refs — branch names, semantic version tags, and commit SHAs.
- GHA cache: The
cache-fromandcache-tooptions use GitHub Actions cache for Docker layer caching, dramatically speeding up rebuilds.
Multi-Platform Builds
Add platforms: linux/amd64,linux/arm64 to the build step for multi-architecture images. This is essential for supporting both x86 and ARM environments (Apple Silicon, AWS Graviton).
Tagging Strategy
The metadata action provides flexible tagging. The example tags produce: myuser/myapp:main for branch pushes, myuser/myapp:1.2.3 for version tags, and myuser/myapp:sha-abc1234 for commit-level tracking.
Use Case
Building and publishing container images for microservices, web applications, or CLI tools. Essential for teams practicing continuous delivery with containerized deployments to Kubernetes, ECS, or similar platforms.