What You Are Building
For pull request number 123, the system creates a Kubernetes namespace pr-123, deploys the branch\'s image into it, exposes it at pr-123.preview.example.com, comments the URL on the PR, and removes everything when the PR is merged or closed. Reviewers, designers and testers click a link instead of checking out a branch.
Namespaces give cheap isolation inside one cluster: separate names for resources, per-namespace quotas and network policies. They are not a hard security boundary against hostile code, so run previews only for trusted contributors or use a separate cluster for untrusted forks.
Prerequisites
- A Kubernetes cluster with an ingress controller, and a wildcard DNS record (
*.preview.example.com) pointing at it. - A wildcard TLS certificate or cert-manager issuing certificates per host.
- A container registry, and CI that builds an image per commit tagged with the commit SHA.
- Credentials for CI to deploy to a preview cluster or namespace set only, never to production.
Manifests with a Template
Keep one template and substitute the PR number. This version uses envsubst, which ships with common Linux distributions (package gettext). Variables: PR, IMAGE, HOST.
# preview/app.yaml.tpl
apiVersion: v1
kind: Namespace
metadata:
name: pr-${PR}
labels:
preview: "true"
pr: "${PR}"
annotations:
preview/expires-at: "${EXPIRES_AT}"
---
apiVersion: v1
kind: ResourceQuota
metadata:
name: preview-quota
namespace: pr-${PR}
spec:
hard:
requests.cpu: "1"
requests.memory: 1Gi
limits.cpu: "2"
limits.memory: 2Gi
pods: "10"
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: pr-${PR}
spec:
replicas: 1
selector:
matchLabels: { app: web }
template:
metadata:
labels: { app: web }
spec:
containers:
- name: web
image: ${IMAGE}
ports:
- containerPort: 8080
env:
- name: APP_ENV
value: preview
resources:
requests: { cpu: 100m, memory: 256Mi }
limits: { cpu: 500m, memory: 512Mi }
readinessProbe:
httpGet: { path: /health, port: 8080 }
initialDelaySeconds: 5
---
apiVersion: v1
kind: Service
metadata:
name: web
namespace: pr-${PR}
spec:
selector: { app: web }
ports:
- port: 80
targetPort: 8080
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: web
namespace: pr-${PR}
spec:
ingressClassName: nginx
tls:
- hosts: ["${HOST}"]
secretName: preview-wildcard-tls
rules:
- host: ${HOST}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: web
port:
number: 80Points to notice: a ResourceQuota so one runaway preview cannot starve the cluster, resource requests and limits on every container (quotas require them), a readiness probe so the PR comment appears only when the app answers, and an expiry annotation used by the cleanup job below. The TLS secret must exist in each namespace; copy it in the workflow or use cert-manager.
GitHub Actions Workflow
# .github/workflows/preview.yml
name: preview
on:
pull_request:
types: [opened, synchronize, reopened, closed]
concurrency:
group: preview-${{ github.event.number }}
cancel-in-progress: true
permissions:
contents: read
pull-requests: write
env:
PR: ${{ github.event.number }}
REGISTRY: ghcr.io/${{ github.repository }}
jobs:
deploy:
if: github.event.action != 'closed'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build and push image
run: |
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
docker build -t "$REGISTRY:pr-$PR-${{ github.sha }}" .
docker push "$REGISTRY:pr-$PR-${{ github.sha }}"
- name: Configure cluster access
run: |
mkdir -p ~/.kube
echo "${{ secrets.PREVIEW_KUBECONFIG }}" > ~/.kube/config
chmod 600 ~/.kube/config
- name: Deploy preview
run: |
export IMAGE="$REGISTRY:pr-$PR-${{ github.sha }}"
export HOST="pr-$PR.preview.example.com"
export EXPIRES_AT="$(date -u -d '+7 days' +%Y-%m-%dT%H:%M:%SZ)"
envsubst < preview/app.yaml.tpl | kubectl apply -f -
kubectl -n "pr-$PR" rollout status deployment/web --timeout=180s
- name: Comment URL
uses: actions/github-script@v7
with:
script: |
github.rest.issues.createComment({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.issue.number,
body: `Preview ready: https://pr-${process.env.PR}.preview.example.com`
})
cleanup:
if: github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- name: Configure cluster access
run: |
mkdir -p ~/.kube
echo "${{ secrets.PREVIEW_KUBECONFIG }}" > ~/.kube/config
chmod 600 ~/.kube/config
- name: Delete namespace
run: kubectl delete namespace "pr-$PR" --ignore-not-found --wait=falseSecurity notes: workflows triggered by pull_request from forks do not receive repository secrets by default, which protects your cluster credentials. Do not switch to pull_request_target to get the secrets and then build untrusted code; that is a well-known way to leak credentials. Give PREVIEW_KUBECONFIG permissions limited to creating and deleting preview namespaces, using a dedicated service account and RBAC.
Argo CD Alternative: ApplicationSet Pull Request Generator
If you already use Argo CD, an ApplicationSet can create and delete preview applications by watching pull requests, so CI only needs to build the image:
apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
name: previews
namespace: argocd
spec:
goTemplate: true
generators:
- pullRequest:
github:
owner: acme
repo: shop
labels: ["preview"] # only PRs carrying this label get an environment
requeueAfterSeconds: 120
template:
metadata:
name: "shop-pr-{{.number}}"
spec:
project: previews
source:
repoURL: https://github.com/acme/shop.git
targetRevision: "{{.head_sha}}"
path: deploy/preview
helm:
parameters:
- name: host
value: "pr-{{.number}}.preview.example.com"
destination:
server: https://kubernetes.default.svc
namespace: "pr-{{.number}}"
syncPolicy:
automated: { prune: true, selfHeal: true }
syncOptions: ["CreateNamespace=true"]When the PR closes or loses the label, the generator stops producing the Application and Argo CD removes it. Field names and templating options vary between Argo CD versions, so check the ApplicationSet documentation for yours. The advantage over the workflow approach is that cleanup is declarative and self-healing; the cost is another system to operate.
The Hard Parts
Data
- Stateless first. Start with apps that need only configuration. Add data once the basics work.
- Per-PR database: run a small database in the namespace seeded from a migration plus fixture data. Never copy production data into previews; it creates privacy and compliance exposure.
- Shared dependencies: point previews at a shared staging backend where isolation is not essential, using test accounts and tenant prefixes.
Secrets
Previews should use preview-only credentials with minimal permissions and sandbox third-party accounts (payments in test mode). Sync them from a secret manager with the External Secrets operator or inject at deploy time. Never reuse production secrets.
Cost Control
- Resource quotas and small requests per namespace, as above.
- Expiry: delete previews after a time limit even if the PR is still open. A scheduled job can delete namespaces whose
preview/expires-atannotation is in the past. - Scale to zero after hours, or after inactivity, with a tool that supports it, and wake on request.
- Use a dedicated node pool with cheaper capacity for previews, with taints so production workloads never land there.
- Limit concurrency: a label such as
previewopts a PR in, rather than every draft PR.
Cleanup Safety Net
Closing events can be missed. A nightly job removes namespaces labelled preview=true whose expiry has passed:
#!/usr/bin/env bash
# Delete preview namespaces whose expiry annotation is in the past.
now=$(date -u +%s)
kubectl get ns -l preview=true -o json \
| jq -r '.items[] | [.metadata.name, (.metadata.annotations["preview/expires-at"] // "")] | @tsv' \
| while IFS=$'\t' read -r name exp; do
[ -z "$exp" ] && continue
if [ "$(date -u -d "$exp" +%s)" -lt "$now" ]; then
echo "deleting expired $name"; kubectl delete ns "$name" --wait=false
fi
doneRun it as a Kubernetes CronJob or from a scheduled CI workflow. It requires kubectl, jq and GNU date.
Network Policy and Isolation
By default pods in different namespaces can talk to each other. Add a default-deny NetworkPolicy that allows only ingress from the ingress controller and egress to DNS and the specific backends the app needs. Policies are enforced only if your cluster\'s network plugin supports them.
Checklist
- One namespace per PR with quota, labels and an expiry annotation.
- Image tagged by commit; readiness check before announcing the URL.
- Preview-only credentials; no production data or secrets.
- Cleanup on close, plus a scheduled expiry sweep.
- Network policy and a dedicated node pool.
- Fork PRs handled safely (no secrets, or no previews).
This pairs naturally with platform engineering golden paths and with pod-based teams that own their delivery pipeline. For safe release practices see CI/CD for AI Microservices.
Frequently Asked Questions
What is a preview environment?
A preview environment is a temporary, isolated deployment of the application created automatically for a pull request at its own URL, so reviewers can test the change running instead of reading code. It is deleted when the pull request is closed.
Is a namespace per pull request secure enough?
Namespaces isolate names, quotas and policies, but they are not a hard boundary against hostile code. Use them for trusted contributors, add network policies, and use a separate cluster for untrusted forks.
How do I stop preview environments from costing too much?
Set resource quotas and small requests per namespace, expire previews after a time limit, scale them down when idle, run them on a dedicated cheaper node pool, and let only labelled pull requests create one.
What about databases and secrets in previews?
Use a small database seeded with fixtures or a shared staging backend with test accounts, never production data. Give previews their own low-privilege credentials, preferably sandbox accounts for third-party services.
How do I clean up previews when a webhook is missed?
Annotate each namespace with an expiry time and run a scheduled job that deletes labelled namespaces past their expiry. Also delete on the pull request closed event.