Ship a multi-service app into a customer's Kubernetes cluster
This example builds a whole support desk, with every service and data store, that deploys into each customer's Kubernetes cluster as one versioned release. Tickets, attachments, and background jobs never leave the customer's cluster.
Architecture diagram. Left: Your cloud containing Alien manager, Releases, Helm chart, images, Commands. Right: Customer Kubernetes cluster containing Namespace containing Operator; gateway :8080; dashboard; api; worker; scheduler; postgres; redis; files.
What you build:
- A dashboard, an API, a background worker, and a scheduler, each in its own directory and unchanged.
- Postgres, Redis, and the customer's own bucket for attachments.
- One public gateway; everything else stays on the cluster's private network.
- A
reprocesscommand your backend can call without a public admin endpoint.
Source: examples/full-stack-microservices (TypeScript, Kubernetes).
Why keep the service split
Collapsing a product into one container to ship it rewrites your app and still leaves Postgres, Redis, and a bucket to run somewhere. This example keeps the service graph you already have.
alien.ts lists each service: its code or image, ports, environment, and links. The customer's admin runs one helm install during initial setup, the one-time step with their own credentials. After that, each alien release reaches the cluster without a helm upgrade.
| Resource | Kind | Lifecycle | Built from | Role |
|---|---|---|---|---|
files | Storage | Frozen | Customer's bucket | Attachments and processed artifacts |
postgres | Container | Live | postgres:16-alpine | Issues and file records, 10Gi volume |
redis | Container | Live | redis:7-alpine | Job queue and job status |
api | Container | Live | services/api, TypeScript toolchain | Bun and Hono API |
worker | Container | Live | services/worker, TypeScript toolchain | Processes jobs; reprocess command |
scheduler | Container | Live | services/scheduler/Dockerfile | Calls the API every 60 seconds |
dashboard | Container | Live | services/dashboard/Dockerfile | TanStack Start UI |
gateway | Container | Live | services/gateway/Dockerfile | nginx, the only public endpoint |
Each release can create, update, and replace live resources. The frozen files Storage (created once, never replaced) belongs to the customer's initial setup, so no release can replace or delete it. See Frozen and live resources.
Data services
The stack starts with the bucket. On Kubernetes, Storage maps to a bucket the customer already runs and names at initial setup.
const files = new alien.Storage("files").build()Postgres runs from the public image, with a persistent volume. PGDATA points inside the volume's default mount path, /data:
const postgres = new alien.Container("postgres")
.code({ type: "image", image: "postgres:16-alpine" })
.cpu(0.5)
.memory("512Mi")
.port(5432)
.environment({
POSTGRES_DB: "app",
POSTGRES_USER: "app",
POSTGRES_PASSWORD: "app",
PGDATA: "/data/postgres",
})
.permissions("app")
.persistentStorage("10Gi")
.build()With .persistentStorage(), the container keeps its volume across restarts and replacements.
Redis is an ordinary container with no volume, so its queue is lost if the pod restarts:
const redis = new alien.Container("redis")
.code({ type: "image", image: "redis:7-alpine" })
.cpu(0.25)
.memory("256Mi")
.port(6379)
.permissions("app")
.build()This example models Postgres and Redis as containers to show how an existing service graph maps onto Alien. On AWS, Google Cloud, or Azure you would use the Postgres resource for a managed database instead.
Service names
Every container with .port() gets a Kubernetes Service named after its resource ID. Services reach each other by that name inside the namespace (postgres:5432, redis:6379, api:3000), never through public DNS.
const api = new alien.Container("api")
.code({
type: "source",
src: "./services/api",
toolchain: { type: "typescript" },
})
.cpu(0.5)
.memory("512Mi")
.port(3000)
.environment({
PORT: "3000",
DATABASE_URL: "postgres://app:app@postgres:5432/app?sslmode=disable",
REDIS_URL: "redis://redis:6379",
FILES_BUCKET: "files",
APP_PUBLIC_NAME: "Alien Support Desk",
})
.permissions("app")
.link(files)
.build()apiandworkerbuild from source with the TypeScript toolchain.scheduler,dashboard, andgatewaybuild from their own Dockerfiles withtoolchain: { type: "docker", dockerfile: "Dockerfile" }.
Alien builds all five images on alien build and serves them to the cluster, so the customer needs no access to your registry.
One public entry point
Only the gateway calls .publicEndpoint():
const gateway = new alien.Container("gateway")
.code({
type: "source",
src: "./services/gateway",
toolchain: { type: "docker", dockerfile: "Dockerfile" },
})
.cpu(0.25)
.memory("128Mi")
.port(8080)
.publicEndpoint("web", 8080, "http")
.healthCheck({ path: "/health", method: "GET", timeoutSeconds: 1, failureThreshold: 3 })
.permissions("app")
.build()The gateway is plain nginx, using the in-cluster service names:
/health: answered by nginx./api/*: the API, with the prefix stripped.- Everything else: the dashboard.
upstream api {
server api:3000;
}
upstream dashboard {
server dashboard:3000;
}
server {
listen 8080;
location = /health {
add_header content-type application/json;
return 200 '{"ok":true,"service":"gateway"}';
}
location /api/ {
proxy_pass http://api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
proxy_pass http://dashboard;
# same proxy headers as /api/
}
}Because proxy_pass http://api/ ends with a slash, /api/issues reaches the API as /issues. The dashboard sets VITE_API_BASE: "/api", so the browser calls the API through the same origin.
Records and files
The API waits for Postgres and Redis before it serves traffic, because pods start in any order. waitForStartupDependency retries with a growing delay, capped at 5 seconds, for up to 180 seconds (STARTUP_TIMEOUT_SECONDS):
async function start() {
await waitForStartupDependency("postgres", async () => {
await db.query("select 1")
})
await initializeSchema()
await waitForStartupDependency("redis", async () => {
await redis.ping()
})
Bun.serve({
port,
fetch: app.fetch,
})
console.log(`api listening on ${port}`)
}initializeSchema creates the issues and issue_files tables with create table if not exists, so every replica and every restart can run it.
File uploads go to the files Storage through the storage() binding. Postgres keeps only the object key:
const fileId = randomUUID()
const objectKey = `issues/${id}/${fileId}-${payload.filename}`
await files.put(objectKey, new TextEncoder().encode(payload.content))
const result = await db.query(
"insert into issue_files (id, issue_id, object_key, filename) values ($1, $2, $3, $4) returning *",
[fileId, id, objectKey, payload.filename],
)
return c.json({ file: result.rows[0] }, 201)Only api and worker call .link(files), so only they get the Storage binding. The app profile grants storage/data-read and storage/data-write on files:
.permissions({
profiles: {
app: {
files: ["storage/data-read", "storage/data-write"],
},
},
})Background jobs
Processing an issue is asynchronous. POST /issues/:id/process records the job status in a Redis hash and pushes the job onto a list:
await redis.hset(`issue:${id}:job`, {
status: "queued",
queuedAt: new Date().toISOString(),
})
await redis.lpush("work:issues", JSON.stringify({ issueId: id, requestedAt: Date.now() }))
return c.json({ queued: true, issueId: id })The worker blocks on that list. For each job it:
- Reads the issue.
- Writes a summary to Storage.
- Marks the issue processed in both Redis and Postgres.
const row = issue.rows[0]
const artifactKey = `artifacts/${row.id}/summary.txt`
await files.put(
artifactKey,
new TextEncoder().encode(
`Issue: ${row.title}\n\n${row.body}\n\nProcessed: ${new Date().toISOString()}\n`,
),
)
await redis.hset(`issue:${row.id}:job`, {
status: "processed",
artifactKey,
processedAt: new Date().toISOString(),
})
await db.query("update issues set status = $1, updated_at = now() where id = $2", [
"processed",
row.id,
])If the issue no longer exists, the worker sets the job status to missing and moves on.
GET /issues/:id returns the issue, its files, and the Redis job hash, so you can watch a job go from queued to processed.
An operational command
The worker also exposes a reprocess command, so your backend can requeue an issue without a public admin endpoint:
if (process.env.ALIEN_COMMANDS_URL) {
const receiver = createCommandReceiver()
receiver.command("reprocess", async input => {
if (
typeof input !== "object" ||
input === null ||
!("issueId" in input) ||
typeof input.issueId !== "string"
) {
throw new TypeError("issueId must be a string")
}
const { issueId } = input
await redis.lpush("work:issues", JSON.stringify({ issueId, requestedAt: Date.now() }))
return { requeued: true, issueId }
})
void receiver.run().catch(error => {
console.error("command receiver stopped", error)
})
}.commandsEnabled(true) on the worker injects the ALIEN_COMMANDS_* variables. A container has no runtime in front of it, so the receiver leases commands over outbound HTTPS through the connection of the Operator, Alien's process in the cluster.
The if lets you run the container by hand without those variables: the receiver is skipped and the job loop still runs.
The worker is the only command-capable resource here, so callers don't need a target:
alien commands invoke \
--deployment <deployment-id> \
--command reprocess \
--params '{"issueId": "<issue-id>"}'{ "requeued": true, "issueId": "<issue-id>" }Scheduled work
The scheduler is a loop that calls a private API route every SCHEDULE_INTERVAL_SECONDS (60 in alien.ts), using API_URL: "http://api:3000":
async function enqueueMaintenance() {
const headers = appSecret ? { "x-app-secret": appSecret } : undefined
const response = await fetch(`${apiUrl}/internal/maintenance`, {
method: "POST",
headers,
})
if (!response.ok) {
throw new Error(
`maintenance enqueue failed with HTTP ${response.status}: ${await response.text()}`,
)
}
console.log(await response.text())
}Each call creates a "Maintenance" issue and queues it for the worker. A failed call is logged and retried on the next tick.
For an existing cron process, this is a good first step: keep it as its own container and change how it runs later.
The stack
The stack targets Kubernetes only and adds every resource:
export default new alien.Stack("full-stack-microservices")
.platforms(["kubernetes"])
.add(files, "frozen")
.add(postgres, "live")
.add(redis, "live")
.add(api, "live")
.add(worker, "live")
.add(scheduler, "live")
.add(dashboard, "live")
.add(gateway, "live")
.permissions({
profiles: {
app: {
files: ["storage/data-read", "storage/data-write"],
},
},
})
.build()Check the services locally
This example is not an alien init template, and because the stack targets only kubernetes, it doesn't run under alien dev. Clone the repository and type-check the services from the examples workspace:
git clone https://github.com/alienplatform/alien.git
cd alien/examples
pnpm install
pnpm -C full-stack-microservices test:tsTo run the API by hand, start Postgres and Redis locally and set:
DATABASE_URL=postgres://app:app@localhost:5432/app?sslmode=disable
REDIS_URL=redis://localhost:6379
APP_SECRET=dev-secretThe API listens on PORT, default 3000. Without a Storage binding, the file routes fail; everything else works.
Build, release, and deploy
Build the images and the Helm chart, then publish a release:
cd alien/examples/full-stack-microservices
alien build --platform kubernetes
alien release --platform kubernetesOnboard a customer and send their admin the setup link, a URL that opens the setup page Alien hosts for them:
alien onboard customer-1 --allow admin@customer-1.com --platforms kubernetesThe admin runs initial setup once:
- Chooses Kubernetes in the deployment portal, the page the link opens.
- Saves the generated
values.yamland mapsfilesto a bucket the cluster can reach. - Runs the
helm installcommand from the portal.
infrastructure:
files:
type: storage
service: s3
bucketName: customer-1-filesThe Operator starts, connects out to Alien, and deploys the release into the namespace. See Kubernetes for S3-compatible stores and keeping credentials in a Secret.
Try the running app
Once the deployment shows Running, use the gateway's public URL. Alien's end-to-end suite runs this exact sequence against EKS, GKE, and AKS:
curl https://<gateway-url>/health
# {"ok":true,"service":"gateway"}
curl https://<gateway-url>/api/health
# {"ok":true,"service":"api"}
curl -X POST https://<gateway-url>/api/issues \
-H 'content-type: application/json' \
-d '{"title": "Login fails", "body": "Customer cannot sign in after reset."}'
# 201 {"issue":{"id":"<issue-id>","title":"Login fails","status":"open",...}}
curl -X POST https://<gateway-url>/api/issues/<issue-id>/files \
-H 'content-type: application/json' \
-d '{"filename": "notes.txt", "content": "Steps to reproduce"}'
# 201 {"file":{"id":"<file-id>","object_key":"issues/<issue-id>/<file-id>-notes.txt",...}}
curl https://<gateway-url>/api/files/<file-id>
# {"filename":"notes.txt","content":"Steps to reproduce"}
curl -X POST https://<gateway-url>/api/issues/<issue-id>/process
# {"queued":true,"issueId":"<issue-id>"}
curl https://<gateway-url>/api/issues/<issue-id>
# {"issue":{...,"status":"processed"},"files":[...],"job":{"status":"processed","artifactKey":"artifacts/<issue-id>/summary.txt",...}}The API returns 400 when title, body, filename, or content is missing, and 404 for an unknown issue or file. The last call may show "status":"queued" for a moment before the worker picks the job up.
To read the code, follow one request: gateway, API, worker, then scheduler.
On other platforms
The stack declares only kubernetes. The customer can deploy it into a cluster they already run, or have the portal create a managed EKS, GKE, or AKS cluster first.
Either way, the Operator pulls each release, pulls images through Alien with the deployment's token, ships logs, and leases commands for the worker, all over outbound HTTPS.
To run the same app in a customer's AWS, Google Cloud, or Azure account, add those platforms and replace the in-cluster services that hold state: the Postgres resource for the database, and a Storage that Alien provisions as S3, Cloud Storage, or Blob Storage.
What to change for production
- Move the database password out of
alien.ts.POSTGRES_PASSWORDandDATABASE_URLhard-codeapp:app. Use a generated secret input instead. See Inputs and secrets. - Set
APP_SECRET. The API checksx-app-secreton/internal/maintenanceonly when it's set, andalien.tsdoesn't set it, so anyone who can reach the gateway can callPOST /api/internal/maintenance. Supply it as a secret toapiandscheduler, or keep internal routes off the gateway. - Add authentication at the gateway. No route checks who is calling.
- Persist or replace Redis. It has no volume, so queued jobs are lost when its pod restarts. Add
.persistentStorage()or use a managed queue. - Size Postgres. One replica, 0.5 vCPU, and 512Mi suit a demo. Volume backups are on by default; set the interval and retention you need with
.persistentStorage("10Gi", { backups: { ... } }). - Replace the scheduler's job. It creates a new issue every minute, forever. Replace it with your real periodic task.
Adapt it
Next
Deploy with Flux or Argo CD
Run an Alien deployment in a Kubernetes cluster from Git, with Flux or Argo CD. For your own clusters, and for customers whose platform team installs everything through GitOps.
Encrypt with the customer's key
Create a key in each customer's AWS KMS, Cloud KMS, or Key Vault and encrypt and decrypt with it from your hosted backend, without ever holding the key.