Automating CI/CD Pipelines with GitHub Actions
Deploying code by hand is slow and risky. One missed command or wrong file can break your live app. In modern software teams, we connect our workflow so that every time you push code to GitHub, a robot automatically tests it, packages it into a clean Docker image, uploads it to a container registry, and triggers a safe GitOps deployment.
In this guide, you will learn how to build a complete, production-ready CI/CD pipeline using 100% free and open-source tools: GitHub Actions, Docker, GitHub Container Registry (GHCR), and GitOps.
- How CI (Continuous Integration), CD (Continuous Delivery), and GitOps work together.
- How to write an optimized, multi-stage
Dockerfileto keep images small and fast. - How to build a complete
.github/workflows/ci-cd.ymlpipeline that tests code and pushes images to GHCR. - How to trigger a GitOps deployment automatically by updating your Kubernetes manifest repository.
- Real-world architectural trade-offs, security best practices, and common DevOps interview questions.
1. What Is a CI/CD Pipeline with GitOps?
Think of a CI/CD pipeline like an automated factory assembly line for your code. Instead of developers running tests on their laptops and manually uploading files to a server, the pipeline does the heavy lifting every single time code changes.
When we add GitOps at the end, we stop giving our CI tool direct admin access to our live Kubernetes cluster. Instead, GitHub Actions simply updates a text file (a YAML manifest) in a separate Git repository with the new Docker image tag. An open-source tool inside the cluster (like ArgoCD or Flux) watches that Git repository and pulls the update automatically.
| Stage | What It Does | Tools Used |
|---|---|---|
| Continuous Integration (CI) | Checks out code, restores packages, and runs automated unit tests. | GitHub Actions, dotnet test |
| Container Packaging | Builds a lightweight, secure Docker image and pushes it to a registry. | Docker Buildx, GHCR |
| GitOps Deployment (CD) | Updates the image tag in a config repo; cluster pulls the new version. | Git, ArgoCD / Flux |
2. Practical Implementation & Code
To make this real, let's automate a C# / .NET Web API project. First, we need an optimized Dockerfile. Then, we will write the GitHub Actions workflow that connects everything together.
Part A: Writing an Optimized Multi-Stage Dockerfile
A common mistake is putting the entire SDK (compilers, build tools, and source code) inside your final Docker image. That makes your image huge and slow to deploy. A multi-stage build uses a heavy image to compile the code, and then copies only the final compiled files into a tiny runtime image.
Example 1: Optimized multi-stage Dockerfile
# Stage 1: Build the application using the full SDK
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
# Copy project file first to take advantage of Docker layer caching
COPY ["OrderApi.csproj", "./"]
RUN dotnet restore "OrderApi.csproj"
# Copy remaining source code and publish
COPY . .
RUN dotnet publish "OrderApi.csproj" -c Release -o /app/publish /p:UseAppHost=false
# Stage 2: Create a tiny, secure runtime image
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS final
WORKDIR /app
# Run as a non-root user for better security
USER app
COPY --from=build /app/publish .
EXPOSE 8080
ENTRYPOINT ["dotnet", "OrderApi.dll"]
Part B: The Complete GitHub Actions Workflow
Create a file at .github/workflows/ci-cd.yml in your repository. This workflow has three jobs: test, build-and-push, and trigger-gitops. Notice how each job waits for the previous one to succeed using the needs keyword.
Example 2: Complete CI/CD & GitOps workflow (.github/workflows/ci-cd.yml)
name: CI/CD and GitOps Pipeline
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
# Job 1: Run Automated Tests
test:
runs-on: ubuntu-latest
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Setup .NET 8
uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: Restore and Run Unit Tests
run: |
dotnet restore
dotnet test --no-restore --verbosity normal
# Job 2: Build Optimized Docker Image & Push to GHCR
build-and-push:
needs: test
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout Source Code
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: Build and Push Docker Image
uses: docker/build-push-action@v6
with:
context: .
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
# Job 3: Trigger GitOps Deployment
trigger-gitops:
needs: build-and-push
runs-on: ubuntu-latest
steps:
- name: Checkout GitOps Manifest Repository
uses: actions/checkout@v4
with:
repository: your-org/k8s-gitops-manifests
token: ${{ secrets.GITOPS_PAT }}
- name: Update Image Tag in Kubernetes Deployment
run: |
NEW_TAG="${{ github.sha }}"
sed -i "s|image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:.*|image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${NEW_TAG}|g" apps/order-api/deployment.yaml
- name: Commit and Push to Trigger ArgoCD Sync
run: |
git config user.name "GitHub Actions Bot"
git config user.email "actions@github.com"
git add apps/order-api/deployment.yaml
git commit -m "Deploy order-api:${{ github.sha }}"
git push origin main
Expected output (GitHub Actions Runner Log)
[test] Passed! - Failed: 0, Passed: 24, Skipped: 0, Total: 24 [build-and-push] #12 exporting to image [build-and-push] #12 pushing layers to ghcr.io/your-org/order-api:a1b2c3d [build-and-push] #12 DONE 14.2s [trigger-gitops] [main 9f8e7d6] Deploy order-api:a1b2c3d [trigger-gitops] 1 file changed, 1 insertion(+), 1 deletion(-) [trigger-gitops] To https://github.com/your-org/k8s-gitops-manifests.git [trigger-gitops] 4c5d6e7..9f8e7d6 main -> main
cache-from: type=gha and cache-to: type=gha,mode=max in Job 2. This uses GitHub's built-in cache to save Docker layers between runs, cutting your build time from minutes down to seconds.3. Architecture & Workflow Visualized
Here is how your code travels from your laptop all the way into your live Kubernetes cluster without a single manual deployment step.
Automated CI/CD & GitOps Pipeline Flow
Each stage runs automatically in sequence. If tests fail at Step 2, the pipeline stops immediately so broken code never reaches the container registry or production.
4. Step-by-Step Execution Breakdown
Let's walk through exactly what happens behind the scenes when you run git push origin main.
test job so you can review code safely without publishing unfinished Docker images.main, Job 2 logs into GitHub Container Registry using the automatic secrets.GITHUB_TOKEN. You don't have to manage or rotate Docker Hub passwords manually.${{ github.sha }}—the unique Git commit ID. This guarantees you always know the exact line of code running in production.:latest tag in production GitOps pipelines. If you push a new :latest image, your deployment.yaml file doesn't change, so ArgoCD will not know a new version exists—and rolling back a broken release becomes a nightmare. Always tag with the unique Git commit SHA.5. Hands-On Practice
Test your understanding by extending the workflow above in your own GitHub repository.
Update the test job so that it fails the build if a developer forgets to format their code properly.
Hint: Add a step that runs dotnet format --verify-no-changes (or flake8 / ruff if you are using Python) before running the tests.
Before pushing your Docker image to GHCR, scan it for known OS and package security vulnerabilities using the free, open-source Trivy scanner.
Expected result: The pipeline fails automatically if any CRITICAL vulnerabilities are found in your base image.
Configure a GitHub Environment named production with required reviewers, and attach it to the trigger-gitops job.
Hint: Add environment: production under the trigger-gitops job so a lead engineer must click "Approve" before the GitOps repo is updated.
6. Interview Questions
CI/CD and GitOps are favorite topics for mid-to-senior developer and DevOps interviews. Here is what hiring managers look for.
Answer: A multi-stage build separates the build environment (compilers, SDKs, source code) from the final runtime environment. This drastically reduces the image size—often from 800MB+ down to under 100MB—which makes pushing to registries faster, speeds up Kubernetes pod startup times, and reduces the security attack surface because no build tools exist in production.
Answer: In push-based deployment, the CI tool (like GitHub Actions) holds admin credentials to the production cluster and runs kubectl apply directly. In GitOps (pull-based), the CI tool never touches the cluster. It only commits a new image tag to a Git repository. An agent inside the cluster (like ArgoCD) pulls the change. This is much more secure, provides a complete Git audit trail, and makes rollbacks as simple as running git revert.
Answer: Two main ways: First, structure the Dockerfile so files that rarely change (like .csproj or package.json) are copied and restored before the application source code. Second, enable Docker Buildx caching using GitHub Actions Cache (cache-from: type=gha) so unchanged layers are reused across pipeline runs instead of rebuilt from scratch.
Conclusion
Connecting your tests, Docker builds, container registry, and GitOps manifests into a single GitHub Actions pipeline transforms how you ship software. You eliminate manual human error, get fast feedback on every Pull Request, and keep your production cluster locked down and auditable.
Start small by automating your unit tests first, then layer in multi-stage Docker builds, and finally connect your GitOps repository. Once you experience zero-touch deployments, you will never go back to deploying by hand.
Official Documentation
- GitHub Actions Documentation – Automating Your Workflow
- Docker Documentation – Multi-Stage Builds
- ArgoCD Documentation – Declarative GitOps CD for Kubernetes
Upgradix by Shrash Studio – Learn Technology. Build Your Future.