TechBuzzPro

PR Preview Environments: Build & Tear Down Safely

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Pull request preview environments spin up a live, isolated copy of your app for each PR, so reviewers can click through changes without touching production or shared staging. This guide covers the full lifecycle: creating previews on demand, keeping them in sync with the PR, and tearing them down reliably so you never leak resources or leave stale deployments behind. You'll need a containerized app (Docker or similar), a cloud account (AWS, GCP, Azure, or a PaaS like Heroku or Render), and a CI/CD tool such as GitHub Actions, GitLab CI, or CircleCI.

What You'll Need

  • A Git repository with a CI/CD pipeline already running tests on pull requests.
  • Docker installed locally for testing your container image (optional but recommended).
  • Cloud CLI tools (e.g., aws, gcloud, az) or a PaaS CLI (e.g., heroku, render) with credentials stored as CI secrets.
  • Permissions to create and delete resources in your cloud account (e.g., a dedicated service account with scoped IAM roles).
  • A unique naming scheme for preview environments (e.g., pr-123).

Step-by-Step

  1. Define your preview environment template. Create a Dockerfile and a docker-compose.yml (or a Helm chart / Terraform module) that describes the app, its database, and any other services. The template should read configuration from environment variables so each preview can be customized.
  2. Set up a CI job that triggers on pull_request events. In your CI config, add a job that runs on pull_request (opened, synchronize, reopened) and another on pull_request closed. The job should have access to the PR number via an environment variable (e.g., PR_NUMBER in GitHub Actions).
  3. Generate a unique environment name and URL. Use the PR number to create a slug like pr-42. For the URL, use a subdomain pattern: pr-42.yourdomain.com or a dynamic subdomain from your PaaS.
  4. Build and push the Docker image. In the CI job, build the image with a tag that includes the PR number (e.g., myapp:pr-42) and push it to your container registry. This ensures the preview uses the exact code from the PR.
  5. Deploy the preview environment. Use your cloud CLI or PaaS API to create a new service/app from the image. Pass environment variables like DATABASE_URL (pointing to a fresh database), APP_ENV=preview, and PR_NUMBER. If you use Terraform, apply a plan with the PR number as a variable.
  6. Set up a database (if needed). Create a temporary database for the preview. Use a managed service (e.g., RDS, Cloud SQL) or spin up a database container. For simplicity, many teams use a shared database with a schema prefixed by the PR number, but isolated databases are safer.
  7. Run migrations and seed data. After the app starts, run database migrations (e.g., rails db:migrate, alembic upgrade head) and optionally seed with test data. This step should be part of the CI job after the database is ready.
  8. Post the preview URL as a comment on the PR. Use the GitHub/GitLab API to add a comment like "Preview: https://pr-42.yourdomain.com" so reviewers can click it directly.
  9. Automatically tear down on PR close. In the pull_request closed event, run a CI job that deletes the cloud resources: the app service, the database, and any associated DNS records or load balancers. Use the same PR number to target the right resources.
  10. Add a manual cleanup fallback. Create a script (e.g., cleanup_preview.sh) that deletes a preview by PR number, and run it manually if the automatic teardown fails. Store it in your repo and document how to invoke it.
  11. Monitor and enforce lifecycle. Set a maximum age for previews (e.g., 7 days) and run a scheduled job (e.g., a cron job) that deletes any preview older than that. This catches PRs that are abandoned or never closed.

Common Mistakes

  • Hardcoding the environment name. If you don't include the PR number, multiple PRs will overwrite each other's previews.
  • Forgetting to tear down on PR close. If the teardown job only triggers on merge, closed-but-unmerged PRs will leave resources running.
  • Sharing a single database across all previews. This causes data collisions and makes it impossible to test migrations that alter shared tables.
  • Not cleaning up on CI failures. If the deploy job fails after creating resources, the teardown job might not run. Always use a finally block or a separate cleanup step that runs regardless.
  • Using production credentials in previews. This is a security risk. Use dedicated, low-privilege credentials for preview environments.

Tips

  • Use a unique subdomain per PR (e.g., pr-123.staging.example.com) and set up a wildcard DNS record so you don't have to create DNS entries manually.
  • For databases, consider using ephemeral containers (e.g., PostgreSQL in Docker) if your preview is short-lived. They are easy to spin up and destroy.
  • Add a status check to the PR that shows whether the preview is ready. This prevents reviewers from clicking a broken link.
  • Use infrastructure-as-code (Terraform, Pulumi) to manage preview resources. It makes the deploy and teardown idempotent and reproducible.
  • Set a resource budget (e.g., CPU/memory limits) for previews so a single PR can't consume all your cloud quota.
  • Log the preview URL and environment details to your CI output for easy debugging.

Troubleshooting

  • Preview URL returns 404 or 502. Check that the app started successfully by looking at container logs. Verify that the port is correct and that the load balancer points to the right service. If using a PaaS, confirm the app is in a healthy state.
  • Teardown didn't run automatically. Check your CI logs for the closed event. If the event didn't fire (e.g., PR was deleted), run the cleanup script manually. Also verify that your CI provider supports the closed event (GitHub Actions does, GitLab uses merge_request with state=closed).
  • Database migration fails. Ensure the database is fully ready before running migrations. Add a wait-for-it script or a health check that polls the database port. Also check that the migration is idempotent if you reuse a shared database.
  • Environment variables are missing. Double-check that you're passing them in the deploy command. In CI, use secrets for sensitive values and regular variables for non-secrets. Verify the variable names match what the app expects.
  • Resource limits exceeded. If your cloud account hits quota, the deploy fails. Reduce the number of concurrent previews or use smaller instance types. Consider scaling down idle previews automatically.
  • Stale previews remain after PR is merged. This happens if the teardown job only triggers on closed but the PR was merged (which also triggers closed in GitHub). In GitLab, merged MRs have a different state; make sure your trigger covers both merged and closed.

Frequently Asked Questions

Can I use preview environments with a monorepo?

Yes, but you'll need to detect which sub-project changed and deploy only that part. Use path filters in your CI to trigger the preview job for relevant directories.

How do I handle previews for PRs that are open for a long time?

Set a maximum age (e.g., 7 days) and have a scheduled job that deletes old previews. You can also add a comment on the PR that the preview expired and needs to be redeployed.

Is it safe to run previews against a production database?

No. Always use a separate database. If you must use a shared database, use a unique schema per PR and clean it up after teardown.

What if my app uses WebSockets or background workers?

You'll need to deploy those as part of the preview environment. Use a process manager (e.g., Foreman, supervisord) or a PaaS that supports multiple process types. Ensure the worker connects to the same database and message broker.

Can I preview a PR that changes infrastructure (e.g., Terraform)?

Yes, but be careful. You can run terraform plan in a preview, but applying changes to a shared infrastructure is risky. Instead, use a separate AWS account or a sandbox environment for such PRs.

How do I prevent previews from being accessed by unauthorized people?

Add basic authentication (e.g., HTTP Basic Auth) or IP allowlisting. Many PaaS platforms support this natively. You can also use a reverse proxy that checks a shared secret in the URL.