What are preview environments and how do you run them on Kubernetes?

A preview environment is a short-lived, isolated deployment of an application that is created automatically for each pull request, gets its own URL and is deleted when the pull request is merged or closed. GitLab calls them review apps, and other tools call them ephemeral or per-PR environments. On Kubernetes, a preview environment is usually one namespace per pull request, created by the CI pipeline or by a GitOps generator such as the Argo CD ApplicationSet pull request generator.

Why teams use them

A shared staging environment holds one version of the application at a time. When several pull requests are open, reviewers wait for their turn, or one change breaks staging for everyone. Preview environments remove that queue:

  • Reviewers, designers and product managers click through the actual change before it merges, instead of reading a diff.
  • End-to-end tests run against a full deployment of the branch, not against a mocked backend.
  • A broken branch only breaks its own environment.

The trade-off is cost and operational work. Every open pull request runs a copy of the application, and something has to create, secure and remove each copy reliably.

Choosing the isolation level

ModelWhat each PR getsIsolationStartup and costFits when
Namespace per PRA namespace in a shared clusterNamespaces, RBAC, network policies and quotasFastest and cheapest; shares nodes and cluster add-onsThe app is a set of Deployments and Services and does not install CRDs
Virtual cluster per PRA virtual control plane running in a namespace of a host cluster, for example with vClusterOwn API server; can install its own CRDs and operatorsSlower to start; one extra control plane per PRThe app ships operators or cluster-scoped resources
Cluster per PRA complete Kubernetes clusterFullSlowest and most expensiveTesting cluster-level changes such as CNI, ingress controller or Kubernetes version upgrades

Most teams start with a namespace per pull request. The Kubernetes namespace docs describe what is and is not namespaced, and the article on Kubernetes multi-tenancy compares namespaces with virtual control planes in more detail.

Creating environments from CI

The simplest setup uses pipeline events. On a pull request push, the pipeline builds the image and runs something like:

bash
helm upgrade --install app-pr-123 ./chart \
  --namespace preview-pr-123 --create-namespace \
  --set image.digest=sha256:... \
  --set ingress.host=pr-123.preview.example.com

On the pull request’s closed event, a second job runs kubectl delete namespace preview-pr-123. Deleting a namespace deletes every object inside it. The pipeline needs permission to create and delete namespaces. RBAC cannot restrict namespace creation by name, so an admission policy, such as a ValidatingAdmissionPolicy, can limit the pipeline’s identity to namespaces with a preview- prefix. Never give that access to workflows triggered from forks. The guide to deploying to Kubernetes from CI/CD covers OIDC authentication for these jobs.

Creating environments with Argo CD

With GitOps, the cluster discovers pull requests itself. The ApplicationSet pull request generator polls GitHub, GitLab, Gitea, Bitbucket or Azure DevOps and creates one Argo CD Application per open pull request. When the pull request is closed, merged or loses a required label, the Application is removed.

yaml
generators:
  - pullRequest:
      github:
        owner: myorg
        repo: myapp
        labels: [preview]       # only PRs with this label get an environment
      requeueAfterSeconds: 300
template:
  metadata:
    name: 'myapp-pr-{{.number}}'
    finalizers: [resources-finalizer.argocd.argoproj.io]
  spec:
    source:
      repoURL: https://github.com/myorg/myapp.git
      targetRevision: '{{.head_sha}}'
      path: deploy/preview
    destination:
      server: https://kubernetes.default.svc
      namespace: 'preview-{{.number}}'

Three details matter. The default polling interval is 30 minutes, so lower requeueAfterSeconds or configure the generator’s webhook for GitHub or GitLab. Without the resources-finalizer shown above, deleting an Application leaves its resources running. And a namespace created with the CreateNamespace sync option is not tracked by Argo CD, so it stays behind unless the manifests include the Namespace object or a cleanup job removes it.

Data for preview environments

The application in a preview environment needs a database, and this is where most setups get complicated. Common approaches, from simplest to most realistic:

  • An empty database per environment, created by the chart, with schema migrations and a seed script that loads fixtures. Fast and fully isolated.
  • A restored snapshot of anonymized data. More realistic, but restores take time and the snapshot pipeline must reliably remove personal data.
  • A shared staging database. Cheap, but schema migrations in one pull request can break every other environment.

Do not copy unmasked production data into preview environments. They run unreviewed code, often with debug settings, and are less protected than production.

URLs and access control

Each environment needs a hostname, usually derived from the pull request number or branch, under a wildcard DNS record such as *.preview.example.com. A single wildcard certificate avoids issuing a certificate per pull request. Every certificate from a public CA is published in Certificate Transparency logs, so per-PR certificates announce each new environment’s hostname to anyone who watches the logs.

A hard-to-guess URL is not access control. Put preview environments behind single sign-on with an identity-aware proxy, as shown in the tutorial on restricting access to internal apps and staging environments. Give them non-production credentials only, because the code they run has not been reviewed yet.

Teardown and cost caps

Preview environments that nobody deletes are the main source of runaway cost. Set limits in several places:

  • Delete on merge or close, through the pipeline event or the generator.
  • Expire stale environments. A scheduled job can delete preview namespaces whose pull request has had no activity for a few days. GitLab review apps support this directly with auto_stop_in.
  • Opt in with a label, so only pull requests that need an environment get one.
  • Apply a ResourceQuota per namespace. A resource quota limits CPU, memory and object counts, including services.loadbalancers and persistentvolumeclaims, which create billable cloud resources.
  • Use cheap capacity. Preview environments tolerate interruptions, so they suit spot instances, and idle ones can be scaled to zero.

Check what lives outside the cluster too. Persistent volumes with a Retain reclaim policy and DNS records created by external tools can outlive the namespace.

Preview environments on Cloudfleet

The Cloudfleet node auto-provisioner adds nodes when preview Pods are pending and deletes them when they are no longer needed, so cluster capacity follows the number of open pull requests. CI pipelines authenticate to Cloudfleet Kubernetes Engine (CFKE) with GitHub Actions OIDC tokens instead of a stored kubeconfig. The TextCortex customer story describes a namespace-per-branch setup on CFKE.

On this page