A GitHub Actions workflow that deploys every pull request to its own Cloud Run service with its own Cloud SQL database, comments the URL, and tears everything down when the pull request closes, plus the fork, cost and config pitfalls to plan for.

A preview environment gives every pull request its own running copy of the app, so a reviewer can click through the change instead of guessing from the diff. GitHub Actions can build one with a single workflow file.
Most of that file ends up handling a database per pull request, fork pull requests that get no secrets, and cleanup after branches disappear. This guide builds it on Cloud Run.
Run a workflow on pull_request events that builds an image, creates a database named after the pull request, deploys a Cloud Run service named after the pull request, and comments the URL, then run a second job on the closed event that deletes both. The events docs list the opened, synchronize, reopened and closed activity types the workflow listens for.
The workflow authenticates with Workload Identity Federation, so there are no service account keys in GitHub, and it needs a shared Cloud SQL instance, a database user, a secret with that user's password and two service accounts. The keyless GitHub Actions guide covers the identity pool and provider. Everything else is a handful of commands, run once:
# One-time setup in project my-project
gcloud artifacts repositories create apps --repository-format=docker --location=europe-west1
gcloud iam service-accounts create preview-deployer
gcloud iam service-accounts create preview-runtime
gcloud sql instances create preview-pg --database-version=POSTGRES_17 \
--edition=enterprise --tier=db-g1-small --region=europe-west1
PASS=$(openssl rand -base64 24)
gcloud sql users create app --instance preview-pg --password "$PASS"
printf %s "$PASS" | gcloud secrets create preview-db-password --data-file=-
RUNTIME=serviceAccount:preview-runtime@my-project.iam.gserviceaccount.com
DEPLOYER=serviceAccount:preview-deployer@my-project.iam.gserviceaccount.com
gcloud projects add-iam-policy-binding my-project --member "$RUNTIME" --role roles/cloudsql.client
gcloud secrets add-iam-policy-binding preview-db-password \
--member "$RUNTIME" --role roles/secretmanager.secretAccessor
for role in roles/run.admin roles/cloudsql.admin roles/artifactregistry.writer; do
gcloud projects add-iam-policy-binding my-project --member "$DEPLOYER" --role "$role"
done
gcloud iam service-accounts add-iam-policy-binding \
preview-runtime@my-project.iam.gserviceaccount.com \
--member "$DEPLOYER" --role roles/iam.serviceAccountUser
Store the identity provider's resource name as the repository variable WIF_PROVIDER and allow the repository to impersonate preview-deployer, as described in the keyless guide. The runtime service account only gets Cloud SQL client access and the one secret, so a preview cannot touch anything else in the project.
The workflow below deploys on every push to an open pull request and tears down on close. It assumes the app reads DB_NAME, DB_USER, DB_PASSWORD and INSTANCE_CONNECTION_NAME, connects through the Cloud SQL socket that --add-cloudsql-instances mounts, as described in the Cloud Run connection docs, and applies its migrations on startup.
# .github/workflows/preview.yml
name: preview
on:
pull_request:
types: [opened, synchronize, reopened, closed]
# One run per pull request; a new push cancels the previous deploy.
concurrency:
group: preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
permissions:
contents: read
id-token: write # for Workload Identity Federation
pull-requests: write # for the URL comment
env:
PROJECT: my-project
REGION: europe-west1
PR: ${{ github.event.pull_request.number }}
SERVICE: api-pr-${{ github.event.pull_request.number }}
DB_NAME: app_pr_${{ github.event.pull_request.number }}
SQL_INSTANCE: my-project:europe-west1:preview-pg
IMAGE: europe-west1-docker.pkg.dev/my-project/apps/api:${{ github.sha }}
jobs:
deploy:
if: github.event.action != 'closed'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: google-github-actions/auth@v3
with:
workload_identity_provider: ${{ vars.WIF_PROVIDER }}
service_account: preview-deployer@my-project.iam.gserviceaccount.com
- uses: google-github-actions/setup-gcloud@v3
- name: Build and push the image
run: |
gcloud auth configure-docker europe-west1-docker.pkg.dev --quiet
docker build -t "$IMAGE" .
docker push "$IMAGE"
- name: Create this pull request's database
run: |
gcloud sql databases describe "$DB_NAME" --instance preview-pg >/dev/null 2>&1 \
|| gcloud sql databases create "$DB_NAME" --instance preview-pg
- name: Deploy the preview service
run: |
gcloud run deploy "$SERVICE" \
--image "$IMAGE" \
--region "$REGION" \
--service-account "preview-runtime@$PROJECT.iam.gserviceaccount.com" \
--add-cloudsql-instances "$SQL_INSTANCE" \
--set-env-vars "DB_NAME=$DB_NAME,DB_USER=app,INSTANCE_CONNECTION_NAME=$SQL_INSTANCE" \
--set-secrets "DB_PASSWORD=preview-db-password:latest" \
--labels "preview=true,pr=$PR" \
--no-allow-unauthenticated
- name: Comment the preview URL
env:
GH_TOKEN: ${{ github.token }}
run: |
url=$(gcloud run services describe "$SERVICE" --region "$REGION" --format 'value(status.url)')
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --edit-last --create-if-none \
--body "Preview for ${GITHUB_SHA::7}: $url"
teardown:
if: github.event.action == 'closed'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: google-github-actions/auth@v3
with:
workload_identity_provider: ${{ vars.WIF_PROVIDER }}
service_account: preview-deployer@my-project.iam.gserviceaccount.com
- uses: google-github-actions/setup-gcloud@v3
- name: Delete the preview service and its database
run: |
gcloud run services delete "$SERVICE" --region "$REGION" --quiet || true
gcloud sql databases delete "$DB_NAME" --instance preview-pg --quiet || true
The concurrency block, covered in the concurrency docs, cancels an in-flight deploy when a newer commit arrives or the pull request closes, so the teardown never races a deploy of the same preview. --edit-last --create-if-none keeps one comment per pull request that updates on every push. The service requires authentication, so reviewers call it with curl -H "Authorization: Bearer $(gcloud auth print-identity-token)" or you grant a reviewers group roles/run.invoker.
Cloud Run can also give each pull request a URL on the main service: deploy with --tag pr-42 --no-traffic and the revision gets its own address, such as https://pr-42---api-abcdef.a.run.app, per the traffic migration docs. That keeps the service count down, but every revision is built from the one service template, so --set-env-vars DB_NAME=app_pr_42 on a preview deploy becomes part of the template that the next production deploy starts from. A separate service per pull request avoids that class of mistake at the cost of more services to list and clean up.
GitHub states in the events docs that, with the exception of GITHUB_TOKEN, secrets are not passed to workflows triggered from forked repositories, and that the token is read-only there. The OIDC token for Workload Identity Federation is not available either, so the deploy job fails for forks. Switching to pull_request_target runs with your credentials, and checking out the fork's code in that context hands those credentials to whoever opened the pull request. Most teams skip previews for forks, or deploy them from a workflow a maintainer triggers after reading the diff.
The teardown job runs on closed, which covers merged and abandoned pull requests, but it does not run if the workflow file is missing on that branch, if the job fails, or if someone closes many pull requests while Actions is degraded. A nightly scheduled workflow that lists Cloud Run services with the label preview=true and deletes those whose pull request is no longer open catches the rest, and the same sweep can drop databases that match app_pr_%. Without it, a busy repository accumulates services and databases that keep the shared instance's disk and connection count growing.
Encore brings infrastructure from code, so the preview environment for a pull request is derived from the infrastructure that branch declares, and there is no workflow file, database script or teardown job to maintain. Once the app is linked to GitHub, Encore builds each pull request, runs its tests and creates a preview environment hosted by Encore, named after the pull request, such as pr:72 at https://pr72-$APP_ID.encr.app.

Run in your terminal to get started locally.
The invoices service starts with a migration for its table:
-- invoices/migrations/1_create_invoices.up.sql
CREATE TABLE invoices (
id BIGSERIAL PRIMARY KEY,
customer TEXT NOT NULL,
total_cents BIGINT NOT NULL
);
Next to the usual encore.service.ts that names the service, it declares a database and an object storage bucket, and a pull request that adds this code gets both in its preview, with the migration applied:
// invoices/invoices.ts
import { api } from "encore.dev/api";
import { SQLDatabase } from "encore.dev/storage/sqldb";
import { Bucket } from "encore.dev/storage/objects";
// In a preview environment, both resources exist only for that pull request.
const db = new SQLDatabase("invoices", { migrations: "./migrations" });
export const summaries = new Bucket("invoice-summaries", { versioned: false });
interface Invoice {
id: number;
customer: string;
totalCents: number;
}
export const create = api(
{ expose: true, method: "POST", path: "/invoices" },
async (p: { customer: string; totalCents: number }): Promise<Invoice> => {
const row = await db.queryRow<{ id: number }>`
INSERT INTO invoices (customer, total_cents)
VALUES (${p.customer}, ${p.totalCents})
RETURNING id`;
const invoice = { id: row!.id, customer: p.customer, totalCents: p.totalCents };
await summaries.upload(
`${invoice.id}.json`,
Buffer.from(JSON.stringify(invoice)),
{ contentType: "application/json" },
);
return invoice;
},
);
export const get = api(
{ expose: true, method: "GET", path: "/invoices/:id" },
async ({ id }: { id: number }): Promise<Invoice> => {
const data = await summaries.download(`${id}.json`);
return JSON.parse(data.toString()) as Invoice;
},
);
The preview database starts empty with the branch's schema, or as a copy of another environment's database, such as staging, if you choose one under App Settings, then Preview Environments, in the Platform Dashboard. A frontend developer can point at the preview with a generated client from encore gen client --env=pr:72 --lang=typescript my-app, and Encore's webhooks can notify a service of yours when a preview deploy finishes, which is a good place to start smoke tests. Cron jobs do not run in preview environments, so scheduled work is tested by calling its endpoint directly.
When the pull request merges, the same declarations deploy to your AWS or GCP account, where the database becomes Amazon RDS or Cloud SQL and the bucket becomes S3 or Cloud Storage.
A coding agent that opens a pull request adding a bucket gets a preview where that bucket already exists, so a reviewer tests the agent's change against real infrastructure before anything reaches production.
Best fit: Teams on AWS or GCP that want a working preview with its own database and bucket for every pull request, and reviewers who test changes from a URL in the pull request.
Trigger a workflow on pull_request events with the opened, synchronize, reopened and closed types. On the first three, build an image, create the pull request's database and deploy a service named after the pull request number, then comment its URL. On closed, delete the service and the database.
No, not with this setup, since GitHub does not pass secrets to workflows triggered from forked repositories and gives them a read-only GITHUB_TOKEN, so the workflow cannot authenticate to your cloud. Using pull_request_target to get around that runs untrusted code with your credentials, so most teams build previews for forks only after a maintainer reviews the change.
Separate services are safer when previews need different configuration, even though revision tags give each pull request a URL on the same service, but every revision is created from the shared service template, so an environment variable set for one preview carries into the next deploy unless it is overridden.
Link the Encore app to the GitHub repository in the Platform Dashboard. Encore then builds and tests each pull request and creates a preview environment named after it, such as pr:72, with the infrastructure that branch declares, at https://pr72-$APP_ID.encr.app.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.