You need to implement GitLab environments with review apps that spin up per-merge-request preview deployments on Kubernetes. Each review app needs its own URL, database, and automatic cleanup. Walk through the implementation including dynamic environments and resource management.
Quick Answer
Use dynamic environments with CI_MERGE_REQUEST_IID for unique naming, deploy per-MR Helm releases with isolated namespaces or resource prefixes, configure auto_stop_in for automatic cleanup, and implement environment:on_stop jobs that tear down all provisioned resources.
Detailed Answer
Review App Architecture
Review apps provide isolated preview environments for each merge request, enabling reviewers to test changes without deploying to shared staging. Each review app gets a unique URL (e.g., mr-123.review.example.com), its own database instance or schema, and independent scaling. GitLab tracks these as dynamic environments with automatic lifecycle management.
Dynamic Environment Naming
Use environment: name: review/$CI_MERGE_REQUEST_IID to create unique environments per MR. The URL uses wildcard DNS (*.review.example.com) pointing to an ingress controller, with per-deployment ingress rules routing to the correct service. Each environment appears in GitLab's Environments page with a direct link to the running app and the associated MR.
Resource Isolation Strategy
Two approaches: namespace-per-review (stronger isolation, cleaner cleanup) or shared-namespace with prefixed resources. Namespace-per-review creates a Kubernetes namespace per MR with its own RBAC, network policies, and resource quotas. This prevents one review app from consuming excessive resources and simplifies cleanup (delete the namespace). Database isolation can use PostgreSQL schemas, dedicated Cloud SQL instances (expensive), or ephemeral containers.
Automatic Cleanup
auto_stop_in: 24 hours triggers the on_stop job after 24 hours of inactivity. The on_stop job must clean up ALL resources: Helm release, namespace, DNS records, database, and any cloud resources. Without proper cleanup, review apps accumulate and exhaust cluster resources. Implement a safety net: a scheduled pipeline that finds orphaned review app resources older than 48 hours and deletes them.
Cost Management
Review apps can be expensive if each gets full-size resources. Use minimal resource requests (100m CPU, 128Mi memory), single-replica deployments, and shared infrastructure (one PostgreSQL instance with per-review schemas). Set resource quotas on review namespaces. For expensive dependencies (ML models, large databases), use shared mocked services or read-only replicas.