How to deploy a TypeScript app with Prisma on Uncloud and Cloudflare

Containerize a Hono + Prisma server, deploy it to a VPS with the Uncloud CLI, and put Cloudflare in front for DNS, proxying, and wildcard TLS.

, updated

Uncloud is a lightweight tool that turns your Docker hosts into a small cluster: a WireGuard mesh between machines, a built-in Caddy reverse proxy for zero-downtime HTTPS ingress, and a uc CLI that deploys Compose-style services with rolling updates. It sits nicely between “one Docker Compose file on a VPS” and Kubernetes.

This guide deploys a TypeScript server app — Hono on Node with Prisma ORM v7 talking to Postgres — onto a single VPS, then points Cloudflare at it so you get DNS, an edge proxy/WAF, and wildcard TLS via DNS-01 challenge. Everything is self-hosted except the database, which lives inside the cluster.

How the pieces fit

              Cloudflare edge (your domain)
                DNS · TLS (Full strict) · WAF · cache
                                │  HTTPS
                                ▼
┌────────────────────────────────────────────────────────────────────────────┐
│                       your VPS — an Uncloud machine                        │
│                                                                            │
│    ┌──────────┐                  ┌───────────────┐                         │
│    │  Caddy   │ ────────────────▶│ app (Hono +   │                         │
│    │  :443    │  start-first ·   │ Prisma, tsx)  │                         │
│    └──────────┘  load balanced,  └───────┬───────┘                         │
│                  rolling deploys           5432                            │
│                                          ▼  db.internal                    │
│                                  ┌───────────────┐                         │
│                                  │   Postgres    │                         │
│                                  │   (internal)  │                         │
│                                  └───────────────┘                         │
│                                                                            │
│       only 80/443 exposed — everything else rides the WireGuard mesh       │
└────────────────────────────────────────────────────────────────────────────┘```

- **Uncloud** owns deployment: builds, ships, and rolls your containers across machines.
- **Caddy** (managed by Uncloud) terminates TLS and routes traffic to your service.
- **Cloudflare** owns the domain: DNS records, proxying, and the DNS-01 challenge that gets Caddy its wildcard certificate. Nothing about your VPS's TLS setup has to change when the IP changes.
- **Prisma** stays exactly as you know it locally — the app is a normal Node.js server in a container.

## 1. The app: Hono + Prisma v7

Working example (any TypeScript server works — Express and Fastify follow the same steps).

npm init -y
npm install hono @hono/node-server
npm install @prisma/client@7 @prisma/adapter-pg pg
npm install -D prisma@7 tsx typescript dotenv
Prisma v7's Rust-free client needs driver adapters, so the connection goes through `@prisma/adapter-pg`. Initialize Prisma with an explicit output path (required in v7):
npx prisma init --output ../generated/prisma_client
Set up the schema at `prisma/schema.prisma`:
datasource db {
  provider = "postgresql"
}

generator client {
  provider = "prisma-client"
  output   = "../generated/prisma_client"
}

model User {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  email     String   @unique
  name      String?
}
Create `prisma.config.ts` (the v7 config file):
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
  },
  datasource: {
    url: env("DATABASE_URL"),
  },
});
And the server at `src/index.ts` — two data routes plus a health check Caddy can use later:
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { PrismaClient } from "../generated/prisma_client/client";
import { PrismaPg } from "@prisma/adapter-pg";

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
const prisma = new PrismaClient({ adapter });

const app = new Hono();

app.get("/healthz", (c) => c.text("ok"));

app.get("/users", async (c) => c.json(await prisma.user.findMany()));

app.post("/users", async (c) => {
  const body = await c.req.json<{ email: string; name?: string }>();
  const user = await prisma.user.create({
    data: { email: body.email, name: body.name },
  });
  return c.json(user, 201);
});

serve({ fetch: app.fetch, port: Number(process.env.PORT ?? 3000) });
For local development, point `DATABASE_URL` at a local Postgres (see [how to set up Postgres](/how-do-i/db/setup-postgres/)), then run the first migration and start in watch mode:
npx prisma migrate dev --name init
npx tsx watch src/index.ts
A minimal `tsconfig.json` for type checking (`npm run typecheck`) — `tsx` runs the code directly:
{
  "compilerOptions": {
    "target": "ES2023",
    "module": "NodeNext",
    "moduleResolution": "bundler",
    "strict": true,
    "types": ["node"],
    "noEmit": true
  },
  "include": ["src", "generated"]
}
## 2. Containerize it `Dockerfile` — multi-stage, `node:22-slim` base with the packages Prisma and the health check need:
FROM node:22-slim

RUN apt-get update -y \
 && apt-get install -y openssl curl \
 && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Install dependencies first so this layer caches
COPY package.json package-lock.json ./
RUN npm ci

# Generate the Prisma client (v7 is Rust-free — no engine binaries)
COPY prisma ./prisma
RUN npx prisma generate

COPY . .

EXPOSE 3000
HEALTHCHECK --interval=10s --timeout=3s --start-period=15s \
  CMD curl -fsS http://localhost:3000/healthz || exit 1

# Apply migrations, then start the server
CMD ["sh", "-c", "npx prisma migrate deploy && npx tsx src/index.ts"]
Notes: - `prisma migrate deploy` on container start is the simplest correct way to keep schema in step per deploy. For bigger shops, run migrations as a separate one-off step instead. - `tsx` in `dependencies`-installed dev tooling runs the TypeScript directly. If you prefer a build step, compile with `tsc`/esbuild and run plain `node dist/index.js`. - Put `DATABASE_URL` in the runtime environment (next step) — never bake it into the image. ## 3. Get a server and initialize the cluster Any Linux VPS works (Hetzner, DigitalOcean, a spare box) with SSH access:
brew install psviderski/tap/uncloud     # macOS
# or: curl -fsS https://get.uncloud.run/install.sh | sh
uc version
Point the CLI at your server — this one command does a lot:
uc machine init [email protected]
What it handles: installs Docker, installs the `uncloudd` daemon under systemd, creates the machine in a WireGuard mesh cluster, reserves a domain like `abc123.uncld.dev` in Uncloud DNS, and deploys the global `caddy` service. You'll see output similar to:
Reserved cluster domain: abc123.uncld.dev
[+] Deploying service caddy 1/1
 ✔ Container caddy-c47x on machine  Started

DNS records updated to use only the internet-reachable machines running caddy service:
  *.abc123.uncld.dev  A → 203.0.113.7
That reserved `uncld.dev` subdomain is handy for smoke-testing before you wire up your own domain in step 6. ## 4. Compose file, first deploy Uncloud reads `compose.yaml` from your project and adds three extensions: `x-ports` (ingress via Caddy), `x-caddy` (custom Caddy config), and `x-machines` (placement). Create `compose.yaml`:
services:
  db:
    image: postgres:17
    restart: unless-stopped
    environment:
      POSTGRES_DB: appdb
      POSTGRES_USER: app
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set in .env}
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 5s
      timeout: 3s
      retries: 10
    # NOT published — reachable only inside the cluster

  app:
    build:
      context: .
      dockerfile: Dockerfile
    x-ports:
      # publish the container port via Caddy under this hostname
      - app.example.com:3000/https
    environment:
      DATABASE_URL: postgresql://app:${POSTGRES_PASSWORD:?set in .env}@db.internal:5432/appdb
    depends_on:
      db:
        condition: service_healthy
    # Optional: pin to specific machines in a multi-machine cluster
    # x-machines:
    #   - my-vps

volumes:
  pgdata:
Key points: - **`db.internal`** — services inside the cluster resolve each other by DNS name; no published port needed for the database. (Prefer managed Postgres like Prisma Postgres or Neon? Just point `DATABASE_URL` at it and delete the `db` service.) - **`app.example.com:3000/https`** — Caddy proxies this hostname to your container port 3000 and issues a TLS certificate for it. - **`${POSTGRES_PASSWORD:?}`** — Compose interpolation from your local `.env` file (it isn't shipped; the value is injected into the service spec at deploy time). See step 7 for the secret-provider pattern. Build the image, distribute it to the cluster machines, and deploy:
uc build --push
uc deploy
`uc deploy` shows a plan and does a start-first rolling update — the old container only leaves after the replacement is healthy:
Deployment plan
~ create service db
  ╰── + start container db on machine
~ create service app
  ╰── + start container app on machine
Proceed with deployment to default? [y/N] y
Check on it:
uc inspect app     # service status, machine, IP
uc logs -f app     # migrate deploy output, then server logs
Verify the database went through:
cat backup.sql | uc exec -T db psql -U app appdb
## 5. Caddy inside Uncloud (what you need to know) The `caddy` service is already running as a global service. Useful commands: | Command | What it does | |---|---| | `uc inspect caddy` | Where Caddy runs, which image | | `uc caddy config` | The full generated Caddyfile — invaluable when debugging routing | | `uc caddy cert ls` | Certificates in cluster storage | | `uc caddy deploy --caddyfile global.Caddyfile` | Custom global config without Compose | The Uncloud Caddy image (`ghcr.io/unlabs-dev/caddy-uncloud`) ships with the Uncloud cluster-storage module (certificates are shared between machines) **and the Cloudflare DNS plugin** — that's what step 6 uses. ## 6. Add Cloudflare Assume the domain `example.com` lives on your Cloudflare account (registrar or nameserver transfer — Cloudflare does it free). ### 6.1 DNS record → server (start DNS-only) In the Cloudflare dashboard → **DNS**: add an **A record** `app` → `203.0.113.7`, and set **Proxy status: DNS only** (grey cloud) for now. With a DNS-only record, Caddy can get its `app.example.com` certificate through a normal HTTP-01 challenge and you can validate the whole path first:
curl https://app.example.com/healthz   # → ok
Now create your users through the Prisma-backed route (`POST /users`) and confirm the deployment is live. ### 6.2 Switch on the Cloudflare proxy + wildcard TLS Orange-clouding (`app`) routes traffic through Cloudflare's edge — WAF, cache, bot management — but Cloudflare now terminates TLS, so Caddy's HTTP-01 challenge is no longer dependable. The fix is a **wildcard certificate via DNS-01 challenge**, which works behind the proxy: 1. Create a Cloudflare API token (**My Profile → API Tokens**) scoped to *Zone → DNS → Edit* for `example.com`. 2. In your project, define the secret (this example pulls from 1Password; a file-based or environment approach works too):
secrets:
  cloudflare_api_token:
    x-command: op read "op://prod/caddy/cloudflare_api_token"
3. Add a Compose-managed `caddy` service that overrides the built-in one, following the official pattern (keep `environment`, `volumes`, `x-ports`, and mounts exactly as shown):
services:
  caddy:
    image: ghcr.io/unlabs-dev/caddy-uncloud:0.1.4
    environment:
      CADDY_ADMIN: unix//run/caddy/admin.sock
      CLOUDFLARE_API_TOKEN: secret://cloudflare_api_token
    healthcheck:
      test: curl -fsS -o /dev/null --unix-socket /run/caddy/admin.sock http://localhost/config/
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s
      start_interval: 1s
    volumes:
      - /var/lib/uncloud/caddy:/etc/caddy:ro
      - /var/lib/uncloud/caddy:/data
      - /run/uncloud/api:/run/uncloud/api:ro
      - /run/uncloud/caddy:/run/caddy
    x-ports:
      - 80:80@host
      - 443:443@host
      - 443:443/udp@host
    x-caddy: ./global.Caddyfile
    deploy:
      mode: global
4. `global.Caddyfile` — a wildcard site that gets the cert via the Cloudflare challenge:
{
    storage uncloud
}

# Wildcard cert for all your app hostnames via Cloudflare DNS-01
*.example.com {
    tls {
        dns cloudflare {env.CLOUDFLARE_API_TOKEN}
    }
    respond "No host matched" 404
}
5. Deploy and watch the config:
uc deploy
uc caddy cert ls   # *.example.com — Let's Encrypt
6. In Cloudflare DNS: switch `app` to **Proxied** (orange cloud), and under **SSL/TLS → Overview** set the encryption mode to **Full (strict)** — edge-to-origin TLS is now real, not a Cloudflare self-signed shortcut. Done: user traffic rides Cloudflare → your machine, with the wildcard certificate protecting every future subdomain (`api.example.com`, another service in the cluster, …) — publish another service with any hostname under `*.example.com` and it's covered. ### 6.3 Worth setting while you're in the dashboard - **Always Use HTTPS** (SSL/TLS → Edge Certificates) so `http://` upgrades at the edge. - **Cache Rules** for static assets — JSON API paths usually stay uncached, which is fine. - Real client IPs reach Caddy through `CF-Connecting-IP`; trust your proxy headers accordingly in the app if logging or rate limiting by IP. ## 7. Day 2: deploys, scaling, secrets **Re-deploy** any time — plan, confirm, rolling:
uc build --push && uc deploy
**Scale the app** across machines (Caddy load-balances replicas automatically and health checks gate the routing):
  app:
    deploy:
      replicas: 2
    x-machines:
      - vps-1
      - vps-2
Add the second machine later with `uc machine init [email protected]` — WireGuard, Caddy, and DNS records update on their own. **Secrets instead of `.env` interpolation** — Uncloud resolves `secret://` values at deploy time, which keeps credentials out of your repo and shell environment:
  app:
    environment:
      DATABASE_URL: secret://database_url

secrets:
  database_url:
    x-command: op read "op://prod/app/database_url"
**Run one-off commands:**
uc exec -d app npx prisma migrate deploy       # detached
cat seed.sql | uc exec -T db psql -U app appdb # feed stdin
uc exec app sh                                  # shell in
## Troubleshooting | Symptom | Likely cause | Fix | |---|---|---| | `uc caddy config` shows no `https://app.example.com` site | `x-ports` typo or service unhealthy | Caddy only adds sites for healthy containers — check `uc inspect app`, health check | | Certificate issuing fails, HTTP-01 errors in Caddy logs | Hostname is orange-clouded but you're still on HTTP-01 | Use the DNS-01 wildcard setup from step 6.2 | | `canary` errors: `P1001 can't reach database` | Wrong `DATABASE_URL` host or db isn't up yet | Use `db.internal` with matching Postgres user/port; `depends_on` with `service_healthy` | | Migrations fail on container start | `migrate deploy` needs the migrations folder and `DATABASE_URL` | Confirm `prisma/migrations` was copied into the image (`COPY . .`) and env vars reach the container | | 526 error (Cloudflare) | SSL mode is Full (strict) but origin has no valid cert | Complete the wildcard DNS-01 setup before enabling Full (strict) | | Token errors in Caddy logs | Cloudflare API token lacks Zone → DNS → Edit | Rescope the token; re-deploy with `uc deploy` | ## Related - **[How do I set up Postgres?](/how-do-i/db/setup-postgres/)** — local database for step 1. - **[MCP Flow Architecture](/architecture/mcp-flow-architecture/)** — if this server becomes an MCP tool provider later. ## Further reading - [Uncloud quickstart](https://uncloud.run/docs/getting-started/deploy-demo-app/) and [publishing services](https://uncloud.run/docs/concepts/ingress/publishing-services/) - [Managing Caddy in Uncloud](https://uncloud.run/docs/concepts/ingress/managing-caddy/) — the Compose + Cloudflare wildcard pattern, verbatim - [Prisma ORM v7 in Docker](https://www.prisma.io/docs/guides/v7/deployment/docker) - [Prisma + Cloudflare Workers](https://www.prisma.io/docs/guides/v7/deployment/cloudflare-workers) — if you'd rather go edge-native: same Prisma schemas, driven by driver adapters in Workers (Hyperdrive, D1). Uncloud is for the VPS path; this is the no-server path.