CI/CD Pipeline Guide: From Commit to Production
A practical guide to building CI/CD pipelines with GitHub Actions, testing gates, deployment strategies, and rollback procedures.
Overview
CI/CD is the backbone of modern software delivery — the difference between a team that ships when someone remembers to run the deploy script and a team where every merge produces a tested, verified artifact ready for production. Elite performers measured by DORA deploy on demand — a dozen times a day or more for the best teams — while low performers batch changes into risky monthly releases. The tool that separates them isn’t secret: it’s a well-designed pipeline.
This guide covers how to build one: the stages every pipeline needs, a production-ready GitHub Actions workflow you can adapt, how to pick a deployment strategy, and how to roll back safely when something slips through. It assumes a working repo and basic YAML reading skills; everything else gets explained as it appears. If you’re designing a pipeline from scratch, the CI/CD pipeline design template pairs well with this guide — this is the how, that’s the spec.
When to Use
The investment pays off fastest when the manual path is already hurting. If any of these sound familiar, a pipeline is overdue:
- You deploy code more than once per week — the manual cost already far exceeds the setup cost
- Two or more developers share the same codebase and keep stepping on each other’s changes
- You need confidence that a merge won’t break production at 3 a.m.
- You want to eliminate “deploy day” as an event on the team calendar
For alternatives, see the guide to CI/CD with GitHub Actions for a platform-specific deep dive.
Core Concepts
Continuous Integration (CI)
Automatically build and test code on every commit. The goal is feedback speed: a broken change should be reported in minutes, while the author still remembers what they did. Everything that can fail fast — lint, type checks, unit tests — runs here. CI earns its keep not by catching every bug but by making the cost of being wrong small and immediate.
Continuous Deployment (CD)
Automatically deploy validated code to production. Don’t confuse it with Continuous Delivery, which stops one step short: the artifact is always deployable, but a human approves the release. Most teams should start with delivery and graduate to deployment once monitoring and rollback are proven.
Pipeline Stages and Gates
| Stage | Purpose | Typical Tools | Gate |
|---|---|---|---|
| Lint | Code quality | ESLint, Prettier, Black, SonarQube | Zero new errors |
| Test | Verify behavior | Jest, pytest, JUnit, Vitest | Pass rate + coverage threshold |
| Build | Create artifacts | Docker, Vite, Webpack, Maven | Artifact builds and is tagged |
| Security | Scan vulnerabilities | Trivy, Snyk, OWASP ZAP | No CRITICAL/HIGH |
| Deploy | Release to environment | GitHub Actions, ArgoCD, Terraform | Health checks + approval |
Each stage ends in a gate — a condition the run must satisfy before continuing. A gate that lets bad code through has failed its only job, which is why effective gates stop the pipeline rather than log a warning and continue.
Solution: A Production-Ready GitHub Actions Pipeline
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm run lint
- run: npm run test:ci
- run: npm run build
security:
runs-on: ubuntu-latest
needs: test
steps:
- uses: actions/checkout@v4
- uses: aquasecurity/trivy-action@master
with:
scan-type: 'fs'
deploy-staging:
runs-on: ubuntu-latest
needs: [test, security]
if: github.ref == 'refs/heads/main'
environment: staging
steps:
- uses: actions/checkout@v4
- run: ./scripts/deploy.sh staging
deploy-production:
runs-on: ubuntu-latest
needs: deploy-staging
if: github.ref == 'refs/heads/main'
environment: production
steps:
- uses: actions/checkout@v4
- run: ./scripts/deploy.sh production
The shape matters more than the syntax: test produces the confidence, security runs in parallel so it doesn’t block the critical path, deploy-staging only runs on main (PRs get CI but never a deploy), and deploy-production sits behind an environment — which on GitHub means required reviewers, audit trail, and environment-scoped secrets. On GitLab the same structure maps to stages ordering, only: [main], and when: manual on the production job.
Reading the workflow top to bottom: on scopes the run to main and pull requests — pushes to feature branches don’t waste runner minutes. The test job chains lint → unit tests → build because each is a gate for the next; a lint failure exits in seconds instead of paying for a full test run. security declares needs: test not because it depends on test output, but because running scans on code that doesn’t compile is wasted work — you can also make it parallel if your runners are cheap. deploy-staging and deploy-production carry if: github.ref == 'refs/heads/main' so PRs get validated but can’t deploy — the single most misconfigured line in homegrown pipelines. Between staging and production you’d normally add an integration-test job; it’s omitted here for brevity but shown in the companion workflow.
Companion files: the cicd-pipeline-guide companion repo packages this workflow plus a rollback script ready to adapt.
Deployment Strategies
1. Rolling Deployment
Gradually replace old instances with new ones.
Pros: Zero downtime, simple. Cons: Rollback takes time, version coexistence issues — old and new serve traffic at once, so your API must tolerate both.
2. Blue-Green Deployment
Maintain two identical environments; switch traffic instantly.
Pros: Instant rollback, zero downtime. Cons: Double infrastructure cost — worth it for user-facing systems where minutes of bad traffic are expensive.
3. Canary Deployment
Release to a small subset of users first — typically 1-5%, then 25%, then 100%.
Pros: Risk mitigation with real-user monitoring; the blast radius stays small while metrics validate. Cons: Complex routing (service mesh or ingress weights), longer total deploy time.
Choose based on what a bad deploy costs you: rolling when versions coexist safely, blue-green when you need instant rollback, canary when a subtle regression could hide from smoke tests. For an in-depth treatment, see the deployment strategies guide.
Rollback Procedures
Automatic Rollback Triggers
- Error rate exceeds threshold (e.g., >1%)
- Latency p99 exceeds threshold (e.g., >500ms or 2x baseline)
- Critical health check fails
- Manual approval not received within timeout
Rollback Commands
# Kubernetes rollback to previous ReplicaSet
kubectl rollout undo deployment/my-app
# Or to a specific revision
kubectl rollout undo deployment/my-app --to-revision=3
# Git revert the offending change (rebuilds through the pipeline)
git revert HEAD
Two rules make rollbacks work when it matters. First, practice them: a rollback path never tested is a hope, not a plan — schedule a drill where you deliberately deploy a bad build and watch it roll back. Second, rollback should be boring: if it requires editing files or asking permission in chat, it’s too slow for a 3 a.m. incident. The cicd-pipeline-setup recipe includes a runnable version of these commands.
What Works
- Fail fast: Run the cheapest, fastest checks (lint, unit tests) first — a lint failure shouldn’t cost a full test suite run.
- Parallelize: Independent jobs (test, security, build) run in parallel; only deploys serialize.
- Use environments: Required reviewers on production give you approval gates and an audit trail for free.
- Cache aggressively: Cache dependencies and build layers — Docker layer caching alone cuts build time by half or more.
- Store artifacts: Keep every build output tagged and traceable; the artifact you deploy to prod should be bit-identical to what passed staging.
- Notify on failure: Alert the team immediately — a pipeline that fails silently becomes a pipeline nobody trusts.
Anti-Patterns
- Deploying without tests — you don’t have CI/CD, you’ve got automated hope.
- The same pipeline logic for all environments — staging and production differ in data, scale, and blast radius; parameterize, don’t copy.
- Manual steps in the deploy path — every manual step is a step that gets skipped under pressure.
- No rollback plan — see the drill rule above.
- Ignoring pipeline failures — flaky jobs get muted, muted jobs get ignored, and the pipeline becomes decoration.
- Deploys that only run on someone’s laptop — if the laptop wins, the pipeline loses.
When Pipelines Fail: Common Failure Modes
Pipelines fail in predictable ways. Knowing which failure you’re looking at changes the response:
| Failure mode | Symptom | Likely cause | Response |
|---|---|---|---|
| Flaky test | Passes locally, fails in CI randomly | Timing, shared state, network | Quarantine, fix root cause, never retry-and-merge |
| Slow drift | Pipeline time creeps 8 → 20 min | Dependency growth, no caching | Measure per stage, add caches, split slow suites |
| Credential expiry | Deploy fails after months of working | Rotated token nobody tracked | Centralize secrets, alert before expiry, prefer OIDC |
| Environment drift | ”Works in staging” | Manual changes in prod | Infra as code, scheduled drift detection |
| Registry outage | Build can’t pull base image | External dependency down | Mirror critical images, retry with backoff |
| Silent skip | Deploy “succeeds” but nothing changed | Wrong if condition | Verify post-deploy artifact version |
Two of these deserve emphasis. Flaky tests are the most corrosive failure: once people learn a red build might be a false alarm, they start merging through real failures — the pipeline’s credibility is gone. Track flake rate per test; anything over ~1% gets fixed or deleted. Drift is the quieter one: the pipeline still passes, but the world it deploys into has changed — a manually tweaked prod setting, a deprecated base image tag. Periodic terraform plan and image rescans catch it before the incident does.
Environment Management
A well-structured pipeline treats environments as cattle, not pets. Each environment should be created from the same infrastructure code — same Terraform, same manifests, different parameters.
Environment Matrix
| Environment | Purpose | Data | Access |
|---|---|---|---|
| Local | Developer iteration | Synthetic / seeded | Developer only |
| CI | Automated testing | Ephemeral test data | CI service account |
| Staging | Pre-production validation | Anonymized production snapshot | Team leads |
| Production | Live users | Real user data | On-call engineers |
Configuration per Environment
Use environment-specific config files or variables rather than branching pipeline logic:
# .env.local
DATABASE_URL=postgres://localhost/dev_db
LOG_LEVEL=debug
# .env.staging
DATABASE_URL=postgres://staging.internal/staging_db
LOG_LEVEL=info
# .env.production
DATABASE_URL=postgres://prod.internal/prod_db
LOG_LEVEL=warn
Never commit secrets to Git. Use secret stores (AWS Secrets Manager, HashiCorp Vault, GitHub Secrets) and inject at runtime — the security best practices guide covers secret hygiene in depth.
Database Migrations in CI/CD
Run migrations as a separate pipeline job, not inside the application startup — a startup migration on 20 pods means 20 concurrent schema changes:
- Before deploy: Run migrations against the target environment
- Verify: Health check confirming schema version matches what the app expects
- Deploy: Only proceed if the migration succeeds
- Rollback plan: Have a downgrade script ready — and prefer backward-compatible changes (expand-then-contract) so the old code keeps working during the rollout
Monitoring & Observability
A pipeline without observability is flying blind. Integrate these checks:
- Synthetic tests after production deploy — ping the critical endpoints, don’t just check that the pod started
- Error rate baseline: Compare post-deploy error rate to the pre-deploy baseline, not to zero
- Performance regression: Alert if p95 latency rises more than ~20% after deploy
- Smoke tests: A minimal happy-path test immediately after deployment, before declaring success
Track the four DORA metrics to know whether the pipeline itself is improving: deployment frequency, lead time for changes, change failure rate, and time to restore service. If frequency rises while change failure rate stays flat or drops, the pipeline is working.
| DORA metric | Elite | High | Medium | Low |
|---|---|---|---|---|
| Deployment frequency | On demand (1+/day) | Weekly–monthly | Monthly–6mo | < 6 months |
| Lead time for changes | < 1 hour | 1 day–1 week | 1–6 months | > 6 months |
| Change failure rate | 0–15% | 16–30% | 31–45% | > 45% |
| Failed deployment recovery | < 1 hour | < 1 day | 1 day–1 week | > 1 week |
Two practical notes on instrumenting this. First, measure pipeline health metrics alongside product metrics: stage durations, queue wait time, flake rate, cache hit ratio. A pipeline whose median duration doubles over a quarter is a pipeline being abandoned in slow motion. Second, cache hit ratio is the tuning metric with the best effort-to-impact ratio on hosted runners — dependency caches that miss on every build are the most common cause of slow pipelines and the cheapest to fix.
Scaling the Pipeline
The starter pipeline above handles a single service well. Growth forces three conversations.
Monorepos change the economics of “build everything on every commit.” Path filters (paths: on triggers, or dorny/paths-filter per job) let changed services run their own pipelines while untouched ones skip entirely. The cost is complexity in required checks — mark skipped-but-required jobs with a “no changes” success job, or branch protection blocks merges forever.
Matrix builds multiply coverage without duplicating config: one strategy.matrix over Node versions, OS images, or regions runs the same job N ways. Keep matrices small — each axis multiplies runner minutes, and a 4×3 matrix is twelve bills.
Self-hosted runners make sense when builds need large caches, GPU access, or private network reach. They trade the platform’s isolation for your responsibility: persistent state between jobs, harder credential hygiene, and the security posture covered in the CI/CD security guide. Default to cloud-hosted unless you can name the specific need.
The last scaling pressure is cultural, not technical: as teams multiply, the pipeline becomes shared infrastructure. Someone must own it — a platform team, a guild, an explicit owner — or it rots the same way unowned code does.
Cost and speed tuning deserves a standing agenda item, not a crisis project. Runner minutes cost money and pipeline minutes cost attention; the usual wins in rough order of effort: dependency caches, Docker layer caching (cache-from/cache-to), concurrency groups that cancel superseded runs on the same branch, path filters, splitting test suites by duration rather than by file, and right-sizing runs-on labels so lint jobs don’t grab 8-core runners. Revisit quarterly — usage patterns drift faster than configs.
Keep Improving
A pipeline is software — it drifts. Review your stage durations monthly, watch which gates fire and which never do, and treat flaky tests as bugs in the pipeline itself. The teams that ship fastest aren’t the ones with the most tooling; they’re the ones whose pipeline is boring enough to trust.
Set a review cadence while you’re at it. Quarterly works for most teams: pull the last quarter’s failure data, pick the stage that wastes the most time, and fix that one thing. Pipelines improve the same way code does — in small, measured increments, not rewrites.
Further Reading
- GitHub Actions documentation — workflows, environments, OIDC, and required reviewers
- GitLab CI/CD documentation — stages,
when: manual, protected environments - DORA research — the metrics behind elite delivery performance
- Kubernetes deployments — rolling updates and rollback mechanics
- Argo Rollouts — canary and blue-green delivery with automated analysis
Frequently Asked Questions
How long should a CI pipeline take?
Target under 10 minutes for feedback; under 5 is ideal. Longer pipelines get bypassed — developers start skipping local checks and merging anyway.
Should I deploy on every commit?
Yes, if your tests and monitoring are reliable. Otherwise deploy on merge to main — but measure how long changes sit undeployed, because batching is how small problems turn into big incidents.
What's the difference between Continuous Delivery and Continuous Deployment?
Continuous Delivery means the code is always deployable; a human approves each release. Continuous Deployment means every validated change ships automatically. Delivery is the sensible starting point — deploy automatically once you've proven your gates.
How do I handle database schema changes in CI/CD?
Run migrations before deployment, keep changes backward-compatible when possible, and have rollback scripts ready. Never drop a column in the same deploy that stops reading it — expand first, contract later.
What should I do when a production deployment fails?
Follow this order: 1) Alert the on-call team, 2) Assess whether rollback is needed, 3) Execute rollback or forward-fix, 4) Document the incident, 5) Run a post-mortem within 48 hours. Forward-fix only when the fix is smaller and safer than the rollback.
How do I get started with this in an existing project?
Start with a small, isolated part of your codebase — one module or service. Apply the pipeline shape from this guide, measure the impact on deploy frequency and failure rate, then expand. A working pipeline on one service beats a perfect design covering none.
How do I set up automatic rollback?
Use progressive delivery tooling — Argo Rollouts or Flagger — with metric analysis against Prometheus: if error rate exceeds 1% or p99 latency doubles baseline for two minutes, roll back automatically. The manual fallback is kubectl rollout undo. Either way, document the criteria in a runbook — rollback should take under 30 seconds.
Does this design translate to GitLab CI or Jenkins?
Yes — the shape is platform-agnostic. On GitLab, stages replace needs ordering, rules:if replaces if: conditions, and when: manual plus protected environments cover the approval gate. On Jenkins, a declarative Jenkinsfile with stage blocks and input steps does the same job. What's worth keeping identical across platforms: fast gates first, deploys only from main, and a human checkpoint before production.
Related Resources
Complete Guide to CI/CD with GitHub Actions
Build CI/CD pipelines from scratch with GitHub Actions. Covers workflows, runners, matrix builds, caching, secrets, environments, deployment strategies, and reusable workflows.
GuideDeployment Strategies Compared: Blue-Green, Canary, Rolling
A practical guide to deployment strategies: rolling, blue-green, canary, shadow and feature flags. Minimize risk and rollback time when releasing to production.
GuideComplete Guide to GitOps with ArgoCD
Deploy Kubernetes apps with GitOps and ArgoCD: installation, ApplicationSets, sync strategies, Helm/Kustomize, RBAC, and multi-cluster.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.
DocCI/CD Pipeline Design Template
A template for documenting CI/CD pipeline stages, gates, environments, deployment strategies, rollback procedures, and security scanning.
RecipeCI/CD Pipeline Setup
Set up automated CI/CD pipelines for testing, building, and deploying applications with GitHub Actions and what works.