Docker Build & Push

๐Ÿ”ฅ Vibe Prompt

"Add Docker build and push to ghcr.io steps in a GitHub Actions workflow."

- name: Login to GitHub Container Registry
  uses: docker/login-action@v3
  with:
    registry: ghcr.io
    username: ${{ github.actor }}
    password: ${{ secrets.GITHUB_TOKEN }}

- name: Build and push
  uses: docker/build-push-action@v5
  with:
    context: .
    push: true
    tags: |
      ghcr.io/${{ github.repository }}:latest
      ghcr.io/${{ github.repository }}:${{ github.sha }}

- name: Deploy to K8s
  run: |
    kubectl set image deployment/my-app app=ghcr.io/${{ github.repository }}:${{ github.sha }}
    kubectl rollout status deployment/my-app --timeout=5m

Full CD Pipeline

A complete CD pipeline: test โ†’ build โ†’ push โ†’ deploy โ†’ verify.

Chapter Summary

  • Understand core concepts and principles
  • Master implementation methods and techniques
  • Familiar with common issues and solutions
  • Able to apply in real projects

Further Reading

  • Official documentation and API references
  • Open source examples on GitHub
  • Technical books and online courses
  • Community discussions and tech blogs

Implementation Example

Basic Example

# This section provides a complete implementation example

Steps

  1. Setup: Configure development environment
  2. Data: Prepare required data
  3. Implementation: Build core functionality
  4. Testing: Verify correctness
  5. Optimization: Improve performance

Common Errors

| Error Type | Cause | Solution | |------------|-------|----------| | Compilation | Syntax | Check code syntax | | Runtime | Environment | Verify dependencies installed | | Logic | Algorithm | Step-by-step debugging | | Performance | Efficiency | Use profilers |

Code Example

import sys

def main():
    print("Hello, World!")

if __name__ == "__main__":
    main()

References

  • Official documentation
  • API reference
  • Open source examples
  • Community discussions

Key Points

  • Understand the core concepts thoroughly
  • Practice with hands-on code examples
  • Apply knowledge to real-world problems
  • Review and reinforce through exercises

Further Learning

Docker Push Workflow

Here is a complete GitHub Actions workflow that builds and pushes a Docker image:

name: Build and Push Docker Image

on:
  push:
    branches: [main]
    tags: ['v*']

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: Extract metadata (tags, labels)
        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,prefix=
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push Docker image
        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

Multi-Architecture Builds

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Build and push (multi-arch)
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm64,linux/arm/v7
          tags: ${{ steps.meta.outputs.tags }}

Container Registries

| Registry | URL | Authentication | Use Case | |----------|-----|---------------|----------| | GitHub Container Registry | ghcr.io | GITHUB_TOKEN | Public/open source | | Docker Hub | docker.io | Docker Hub token | General purpose | | Amazon ECR | acct.dkr.ecr.region.amazonaws.com | AWS IAM | AWS deployments | | Google Artifact Registry | region-docker.pkg.dev | GCP service account | GCP deployments | | Azure Container Registry | acrname.azurecr.io | Azure AD | Azure deployments |

Dockerfile Best Practices

# Use specific base image versions (not latest)
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build

# Minimal production image
FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules

# Run as non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1
CMD ["node", "dist/server.js"]

Image Security Scanning

      - name: Scan Docker image for vulnerabilities
        uses: aquasecurity/trivy-action@master
        with:
          image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
          format: 'sarif'
          output: 'trivy-results.sarif'

      - name: Upload Trivy results to GitHub Security
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: 'trivy-results.sarif'

Summary

Building and pushing Docker images in CI/CD automates the container delivery pipeline. Use Docker Buildx for multi-architecture builds, tag images with semantic versions and commit SHA, and scan for vulnerabilities before pushing.

Key takeaways:

  • Use docker/build-push-action for building and pushing
  • Tag images with semantic version and commit SHA
  • Cache Docker layers with type=gha for 50-80% faster builds
  • Multi-architecture builds: amd64 + arm64 + arm/v7
  • Scan images for vulnerabilities (Trivy, Snyk)
  • Use specific base image versions (not latest)
  • Multi-stage builds produce smaller, more secure images
  • Run containers as non-root user
  • Registry options: ghcr.io, Docker Hub, ECR, GAR, ACR

What's Next: Deploy and Rollback

The next chapter covers deployment and rollback strategies โ€” zero-downtime deployments, health checks, and automated rollbacks on failure.

Unlock Full Tutorial

This chapter is paid content. Join the project to unlock over 5000 words of deep analysis, including 10+ god-tier Prompts and real Source Code examples!