Preview Environments for Pull Requests on Kubernetes

A lifecycle-first guide to per-PR Kubernetes previews, from namespace creation to teardown.

Cover illustration for “Preview Environments for Pull Requests on Kubernetes”

Sponsored by Porter

Written by
Ship It Yourself Editors
Published
November 26, 2026
Reading time
9 min read

Preview environments for pull requests on Kubernetes work when the whole lifecycle is designed together, from namespace creation to deletion. A deployed branch alone is not enough. Small engineering teams can build a production-ready workflow without deep knowledge of infrastructure operations if they connect routing, data isolation, security, and teardown as layers.

Why preview environments have become a baseline expectation for engineering teams

Shared staging has a collision problem. One engineer changes checkout, another changes the database schema, and a third deploys over both. A reviewer then sees a broken checkout that none of those changes causes alone. Reviews wait while the team works out who owns what through Slack queues.

Hosted platforms have made an automatic URL per PR an expectation. Teams running backends on Kubernetes already have the building blocks to provide that experience, but Kubernetes does not supply the workflow. The gap leaves teams choosing between staging collisions and bespoke CI/CD pipelines that become another maintenance burden. A consistent lifecycle offers a more manageable path.

The lifecycle every implementation shares, regardless of tooling

Every implementation must handle five moments explicitly. A PR opens or receives a trigger label, an image builds, manifests are rendered and applied, new pushes update the deployment, and closing or merging the PR removes it. Tooling changes how those transitions happen. If the last step is missed, environments keep running after their work is done.

The namespace is the practical unit of application isolation. Creation is nearly instant, and deleting it removes deployments, services, ingresses, PVCs, and secrets without maintaining a separate resource inventory. PersistentVolumes and cloud load balancers may survive, however, depending on reclaim policies and finalizers. Namespace deletion is broad, but not universal.

Rolling updates deploy new commits into the same namespace while keeping the URL unchanged. That gives reviewers one link to bookmark and the automation one environment to update.

Choosing an isolation model before writing any YAML

The first decision is what each PR must own. For a small-to-medium service count, a full-stack copy in a namespace is the starting point. Every preview gets the complete application, with no services or data shared between PRs. Its cost grows with the number of services multiplied by the number of open PRs.

Cluster-scoped changes require a different answer. If a PR changes a CRD version, operator, admission webhook, or cluster RBAC, namespace separation alone does not isolate the change. Two previews can write to the same cluster-scoped object, leaving the second one to sync in control. A virtual cluster gives each PR its own API server and RBAC inside a namespace on the shared host cluster.

That independence adds a control plane to every environment’s application cost. The choice therefore turns on the scope of the change. The full-stack namespace model below works for changes to the application. Changes to how the cluster behaves need the separate API boundary.

Namespace provisioning — the objects every preview namespace needs and why

The previewctl reference implementation starts with ownership and lifecycle metadata. Its Namespace has a managed-by=previewctl label, a PR number, and annotations for the commit SHA, branch, and expiry. These fields give garbage collection something concrete to act on. A namespace name alone cannot tell it whether an environment should still exist.

ResourceQuota bounds CPU, memory, and pod count per preview. Approximately 2 CPUs and 4 GiB is a workable starting budget, with LoadBalancers, NodePorts, and PVCs excluded unless explicitly required. LimitRange supplies default requests and limits where containers omit them. The quota is a protection against competing workloads.

NetworkPolicy provides the boundary that names cannot enforce. A default-deny ingress policy pairs with permission for connections from the ingress controller’s namespace and the preview’s own namespace. Restricted Pod Security and pod settings cover non-root execution, a read-only root filesystem, dropped capabilities, RuntimeDefault seccomp, and no mounted service-account token. A ClusterIP Service behind an Ingress completes the bundle, with its hostname derived from the namespace.

Routing and TLS — getting a stable, shareable URL to every reviewer

Use one wildcard certificate. A wildcard DNS record and TLS certificate for *.preview.example.com cover addresses such as pr-123.preview.example.com. This avoids per-PR DNS changes and certificate requests, including issuance rate limits that can block deployment. The Ingress hostname is stamped from the namespace at render time, before the application starts.

The live URL belongs in a bot comment on the PR. That comment is the hand-off between CI and the reviewer, including non-engineers and AI coding agents. Without it, a running environment can still be practically inaccessible. Authentication in front of the ingress class, through a shared token or SSO passthrough, protects unreviewed code from public indexing or abuse.

Give it pull-requests: write permission on its GITHUB_TOKEN, but never let it check out PR code. The deploy job can check out that code while using a read-only token. This separation keeps the credential used to publish the link away from the code being reviewed.

The database problem — three strategies and when each is the right fit

Choose the data strategy once per project. A shared staging database with per-PR schema prefixes offers the lowest cost but weak isolation. Destructive migrations create a risk of cross-PR contamination. This works for read-heavy changes when the review does not test data integrity between PRs.

An in-namespace ephemeral Postgres StatefulSet gives each preview a separate database. It can load a checked-in dump, needs no external database dependency, and dies with the namespace. The trade-off is dataset fidelity. This suits teams that can review changes against a smaller or synthetic dataset.

Template cloning offers another way to prepare a database per PR. PostgreSQL’s CREATE DATABASE … TEMPLATE command lets the system seed a template once and copy it for each preview. This changes how data is prepared, rather than replacing the need to choose where the database runs. The surrounding isolation and cleanup decisions still apply.

Seed data must be generated, and it must never be copied from production. Preview links travel more freely and have less protection than production systems, so real customer records create a leak risk. Schema migrations belong in a PreSync hook, while seed jobs belong in a PostSync hook. The GitOps toolchain then enforces the ordering.

GitOps automation — wiring ArgoCD ApplicationSets to the pull request lifecycle

ArgoCD’s pullRequest generator polls the repository through the SCM API on a configurable interval. It creates an Application for each matching open PR and removes it when that PR closes. This declares the desired state in place of scripts that tell the system what to create and delete. The same lifecycle pattern applies to other GitOps tools.

An ApplicationSet can combine the stacks touched by a PR with open PRs bearing a trigger label. The resulting combinations define which Applications exist. A label such as preview makes deployment opt-in, so docs-only or config-only changes do not automatically start the fleet. Scope becomes an explicit cost control.

The GitOps directory is the deployment source of truth. When --out is set, previewctl’s render command writes manifests to environments/<ns>/manifests.yaml. Otherwise, it prints them to standard output. ArgoCD syncs the written manifests. When the generator stops returning a closed PR, the configured pruning path removes its Application and namespace.

The policy gate and least-privilege RBAC — keeping unreviewed code from escaping its namespace

Unreviewed code needs boundaries that the system enforces in place of a manual audit for every PR. The render-time policy gate rejects cluster-scoped kinds, references to other namespaces, privileged pods, unpinned images, and variables resembling secrets, including PASSWORD and TOKEN. ClusterRoleBindings are rejected too. These checks fail in CI before the deployment reaches the cluster.

The deployment identity must be limited independently of that gate. Terraform provisions the preview service account with least-privilege access, without permission to create ClusterRoleBindings, read kube-system secrets, or exec into its pods. Restricted Pod Security checks pods at admission, while pod settings remove credentials and capabilities they do not need. NetworkPolicy supplies the runtime separation between previews.

The reference implementation rejects a smuggled ClusterRoleBinding with exit code 2 before it creates the namespace, and it includes a cross-preview connection probe that is refused. The separate deploy and comment jobs protect the write token from malicious PR code. For SOC 2 or HIPAA teams, these controls provide automatically generated, auditable evidence per environment.

Teardown and garbage collection — why the cleanup job is load-bearing infrastructure

Preview systems often fail when it is time to delete an environment. An environment left running after its PR closes keeps consuming resources without helping anyone review code. A scheduled janitor backs up event-driven deletion when lifecycle events are missed. Its decisions must be conservative when repository metadata is incomplete.

The collector should fail if it cannot fetch the complete open-PR list. Missing results are not proof that a PR closed. The reference implementation ignores unmanaged or terminating namespaces, keeps pinned environments, and retains previews with missing or unreadable PR or expiry metadata while reporting the metadata problems. It deletes closed or expired previews and retains only the newest namespace when a renamed branch leaves duplicates.

Expiry provides a separate backstop against abandoned work. Every push refreshes the timestamp, while inactive environments expire after the configured TTL. A hard concurrency cap queues new previews to keep the cluster within its capacity. Idle shutdown and spot or preemptible node pools further reduce the cost of suitable stateless workloads.

Multiplying the per-preview CPU and memory quotas by the maximum concurrent preview count gives the fleet’s worst-case resource budget. That combination makes previews sustainable as a routine service, rather than a pilot that eventually needs a finance conversation.

Handling AI and GPU inference workloads in preview environments

GPU inference breaks the assumption that CPU activity reflects available capacity. Kubernetes does not expose GPU utilization through its default metrics tooling, and a vLLM pod can show low CPU utilization while its GPU is saturated. Preview health and capacity checks need to account for that gap.

Loading model weights into VRAM takes at least tens of seconds, and scaling a large model from zero can take many minutes. Keeping one warm GPU replica per active inference preview avoids that wait, at the cost of idle capacity. Smaller quantized models can also work when the review does not need full-fidelity inference.

Caching model weights on a shared volume avoids pulling them from object storage on every cold start. MIG, or Multi-Instance GPU, and MPS let multiple preview pods share one physical GPU. These choices change what previews cost while keeping the same PR lifecycle and the need for isolation.

What the full build sequence looks like end to end

Diagram: The Six-Layer Build Sequence. Visualizes: Show the six sequential layers of building a production-ready preview environment on Kubernetes, as described in the article.

The implementation sequence starts with namespaces and their guardrails. An ApplicationSet with the pullRequest generator manages a namespace per PR, including ResourceQuota, LimitRange, NetworkPolicy, and restricted Pod Security. The second layer adds wildcard DNS, one wildcard certificate, and authentication in front of the ingress class. That gives the deployed branch a shareable, protected address.

Data is the third layer of the build. The selected per-PR database strategy becomes part of the manifests, with PreSync migrations and PostSync seeding. The fourth layer adds the render-time policy gate and Terraform-provisioned deployment identity. These controls are described after deployment and data, but they must run before unreviewed manifests reach the cluster.

Every namespace receives an expiry timestamp, a scheduled collector enforces lifecycle decisions, and concurrency limits bound the fleet. Idle scale-down and spot capacity apply where the workload tolerates them, with warm inference replicas treated differently. The sixth layer adds virtual clusters only for repositories whose previews modify cluster-scoped behavior.

A preview is complete when closing the PR removes it safely.

This article is sponsored by Porter.

Every new piece from Ship It Yourself, as it's published.

Follow