Cover illustration for “Preview Environments per Pull Request on Kubernetes”

Essay CI/CD Pipelines

Preview Environments per Pull Request on Kubernetes

Isolation, HTTPS, seeded data, and cleanup make previews reviewable.

Preview environments per pull request on Kubernetes need more than a deployment that succeeds. They need isolation, working HTTPS, useful data, and automatic cleanup. Designing those four layers deliberately turns a temporary deployment into something reviewers can trust to show what will ship.

Why PR preview environments fail without deliberate architecture

Teams often add previews to the deployment process they already use and treat them as one more place to send an image. That leaves important gaps between “the container started” and “the feature is ready to review.” A shared namespace lets concurrent PRs overwrite each other’s configuration or service endpoints. A URL without TLS confronts non-engineers with browser warnings or blocks.

The failures extend beyond reaching the application. With an empty or stale database, testing a feature tells reviewers little, while orphaned environments use up cluster capacity until someone clears them out. These are separate problems. Patching one does not solve the others. Each layer needs deliberate design, starting with namespace isolation, then routing and TLS, data seeding, and finally teardown.

Namespace isolation: giving each PR its own slice of the cluster

Use one Kubernetes namespace per pull request, with a deterministic name such as pr-<number> or preview-<branch-slug>. The name must stay stable across reruns and remain unique across open PRs. Everything else depends on that stable identity. It gives deployment, routing, and teardown the same target rather than leaving each stage to work out which resources belong together.

A shared staging namespace breaks that boundary because concurrent PRs share ConfigMaps, Secrets, and service endpoints. One deployment can overwrite another’s resources. Separate namespaces give RBAC rules a scope in which to keep a preview’s service account from touching another PR’s resources. They also provide the boundary for resource controls.

Create the namespace in CI rather than keeping its name in a manually maintained Helm values file. The creation step should succeed if the namespace is missing and silently skip it if it is already there. Apply templated LimitRange and ResourceQuota objects at creation time. LimitRange supplies default CPU and memory requests and limits for containers that omit them, while ResourceQuota caps total namespace consumption. A misconfigured branch should not starve production workloads on a shared cluster.

Label each namespace with preview/pr-number, preview/branch, and preview/owner so cleanup can identify it later. Will many namespaces bloat the cluster? The namespace count is not itself the resource pressure. Idle previews should run minimal replicas, one per service, with quotas containing their actual consumption.

Generating and deploying per-PR Kubernetes manifests

Once the namespace exists, deployment needs three PR-specific parameters, namely the namespace name, image tag, and ingress hostname. Everything else should come from the shared base chart or manifests, and settings for previews should stay in version control. Use the full commit SHA as the image tag. Branch-name tags are mutable and can produce stale image pulls when the registry cache is warm.

A deployment can use helm upgrade --install pr-<number> ./chart --namespace pr-<number> --create-namespace -f preview-values.yaml --set image.tag=<sha> --set ingress.host=pr-<number>.preview.example.com. Keep preview-values.yaml beside the chart, where reviewers of the application can check and audit changes more easily than if CI scripts generated the file.

Kustomize offers another workable approach through a preview overlay that patches the base manifests with the PR-specific namespace and image, and teams that would rather not hand-write either can use Porter, a PaaS for your own AWS, GCP, or Azure account that deploys and manages Kubernetes-based apps. CI updates the image with kustomize edit set image, renders the overlay, and applies it with kubectl apply. Helm supplies values to templates. Kustomize patches a shared base. Either approach should also render the preview’s Ingress from the same PR parameters.

Inside the namespace, services should use their in-cluster DNS names to reach each other. Public hostnames serve a different purpose. Routing internal calls through the public ingress hostname sends them out through the ingress controller unnecessarily, even though both services belong to the same preview.

Ingress routing and automatic TLS for per-PR hostnames

Namespace isolation is invisible to a product manager or designer. A working HTTPS URL is what makes the preview usable. Without TLS, modern browsers warn or block, leaving reviewers to bypass a warning before they can even inspect the feature.

Use wildcard DNS and a wildcard certificate as the practical default. A single record for *.preview.example.com, using an A record or CNAME as appropriate, directs preview traffic to the ingress controller without a DNS change for each PR. Derive each hostname from the namespace name, such as pr-42.preview.example.com. Provision the wildcard certificate through cert-manager using a DNS-01 challenge. This avoids fresh certificate issuance for every preview.

The wildcard certificate can be stored as a Secret in the ingress controller’s namespace for controller-managed TLS. Configure preview Ingress resources to use that wildcard setup. Render each Ingress through the same Helm chart or Kustomize overlay as the application, injecting its hostname from the PR number. Set ingressClassName or kubernetes.io/ingress.class to the preview ingress controller, which may be separate from production. Include rate-limiting annotations when previews share the cluster with production traffic.

Per-PR certificates are an alternative when separate certificates are preferable. Cert-manager can issue a Certificate resource in each namespace using HTTP-01, avoiding DNS-provider integration but adding issuance latency on the first deployment. Wildcard TLS has fewer moving parts for most teams. Post the resulting URL to the PR through a GitHub or GitLab status or comment after ingress creation, while keeping deployment readiness distinct until rollout and seeding finish.

With an empty or stale database, testing a feature tells reviewers little, while orphaned environments use up cluster capacity until someone clears them out.

Data seeding: making preview environments useful for feature review

A reachable application with an empty database is still a poor review environment. Most real features need records and relationships that let a reviewer judge how they work. Data seeding therefore needs to be part of deployment. The choice is how much realism the review needs and how much work the team can support.

Seeding with fixtures is the easiest way to start. A Kubernetes Job in the preview namespace runs a seed script after deployment, loading a checked-in fixture set. This is deterministic, fast, and avoids production data exposure. It works well for teams that know what test data they need and whose needs stay the same. When fixtures become unmanageable, snapshot restore offers more realistic data volumes and schema state, but requires a snapshot pipeline and sanitization to remove PII before data reaches a preview.

A shared read-only staging database has the lowest operational overhead, but weakens isolation. Concurrent PRs depend on the same schema, so a migration for one can break another’s preview. Database placement introduces a related tradeoff. An ephemeral database Pod per namespace provides isolation and follows the namespace’s teardown lifecycle, but consumes cluster resources and is slower to provision. A shared database server with a separate database or schema per PR is faster and cheaper in resources, but needs explicit database cleanup.

Migration order is the sharpest edge in either model. Run the preview migration job before the application starts, using the same migration tooling as in production in place of a shortcut script. Seeding then supplies the records needed for review. For a small team, start with fixtures and an ephemeral in-cluster database. Snapshot restore can come later, when keeping the fixture set up to date becomes more work.

Automatic teardown when a PR is closed or merged

Without automatic teardown, previews steadily turn into orphaned resources. Cluster capacity erodes, costs accumulate, and ownership becomes harder to trace. The source control provider’s PR closed or merged webhook should be the main trigger for cleanup. CI responds by running a teardown job that deletes the namespace.

Scaling down saves some compute, but resources such as ingress configuration and Secrets stay behind. Namespace deletion lets Kubernetes remove namespaced Pods, Services, Ingresses, Secrets, and PersistentVolumeClaims without a separate delete operation for every resource type. Persistent storage needs particular care. The underlying PersistentVolumes are deleted only when their reclaim policy is Delete, so preview storage should not use Retain if the disks are meant to disappear.

Namespace deletion does not cover resources outside that boundary. A shared database server still needs its per-PR database or schema dropped, and preview-specific external secrets or API keys need revocation. The teardown job should also post an “environment torn down” status to the PR. Reviewers then know that the old URL is no longer active.

Webhooks can fail, so event-driven cleanup needs a time-based fallback. A scheduled CronJob can select preview namespaces with kubectl get namespaces -l preview/pr-number, compare their creation timestamps against a configured age threshold, and delete those that exceed it. The labels identify the previews. The timestamps establish their age. This scanner can be a small shell or Python script, or a simple Kubernetes controller.

Wiring the four layers into a CI/CD pipeline

The layers become dependable when one automated pipeline controls their order. Trigger it when a PR opens or receives a push. First build and push the container image tagged with the full commit SHA, then create the namespace idempotently with its labels, resource quota, and default resource limits.

Next, render and apply the manifests with the namespace, image tag, and hostname parameters. Preserve the migration requirement at this stage so the application does not start before its schema is ready. Wait for the rollout to finish with kubectl rollout status before running the data seed Job. Then wait for that Job to finish. Post the preview URL as ready for review only after those gates pass, even if an earlier comment already exposed the hostname.

The close or merge pipeline runs the reverse lifecycle, beginning with namespace deletion. It then drops the per-PR database if there is one, revokes external credentials used just for the preview, and posts the teardown status. Both pipelines need to tolerate reruns. Deploying again should upgrade the environment already in place, while deleting a namespace that is already gone should be a no-op.

Keep the pipeline configuration in the application repository with the chart, whether it uses GitHub Actions, GitLab CI, or an equivalent system. The developers who work on the application need to read and change the environment configuration. A separate operations repository that they cannot access works against that goal. For public repositories, do not expose a production-capable KUBECONFIG to untrusted pull request code.

Running preview environments on a managed Kubernetes platform instead of raw clusters

Small teams pay a real operational cost for maintaining ingress controllers, cert-manager, namespace controllers, and node autoscaling. That work competes directly with product engineering, especially without a dedicated infrastructure engineer. The architecture may be sound while its upkeep is still too much. A managed Kubernetes platform offers another way to run it.

A platform that deploys into the team’s own AWS, GCP, or Azure account can manage the cluster, ingress, TLS, and autoscaling while leaving infrastructure and data under the team’s control. Namespace isolation, quotas, and labels retain their roles. For routing, the team configures the preview hostname pattern instead of provisioning an ingress controller and operating cert-manager itself.

That does not remove every responsibility from CI. The team still owns the teardown trigger and scheduled cleanup fallback, with namespace deletion cascading through platform-managed resources. It also still needs useful seed data and the correct migration sequence.

The tradeoff is an added dependency and abstraction layer. Teams that want full control over every cluster component can implement this architecture on a self-managed cluster. Other teams can have someone else run the cluster and keep the same design. Either way, the durable idea is the same four-part contract with reviewers, namely an isolated environment, working HTTPS, meaningful data, and cleanup when the PR is finished.

Marcus Kwon-Fielding

← Back to Cluster Without Ops