# Agent file: deploy an app to Railway with a custom domain

This file is written for an AI coding agent working in a repository with its owner present. Follow the steps in order and run the check at the end of each step before starting the next. It is complete without the guide it accompanies.

Every fact about Railway here was checked against the pages under Sources on October 10, 2026. Commands, flags and dashboard labels change. If one fails, read the linked page before trying again. Do not guess.

## Goal

The app in this repository builds from a Dockerfile, runs on Railway, passes a health check on every deploy, and answers over HTTPS on the hostname the human chooses.

## Preconditions

Check each one in the repository before changing anything. If one is false, stop and report it.

- The repository is on GitHub and the working tree is clean.
- The app starts with one command and listens on the port in the `PORT` environment variable, or on a fixed port you can name.
- The Railway CLI is installed and the human has already run `railway login`. Ask them to confirm. Do not run the login yourself.
- There is no `railway.json` or `railway.toml`. If one exists, tell the human: Railway documents those files as deprecated and reads them only until December 1, 2026. `railway config migrate` converts them. Wait for a decision before running it.
- Find every environment variable the app reads, and sort the list into public values and secrets.

## Environment variables

Names only. Values are set on Railway by the human or by you for non-secret values.

| Name | Set by | Notes |
| --- | --- | --- |
| `PORT` | Railway, or the Dockerfile | Railway injects it and sends traffic and health checks to it. If the Dockerfile fixes a port, the custom domain must target the same port. |
| `HOSTNAME` | Dockerfile | `0.0.0.0` for a standalone Next.js server, so it binds all interfaces. |
| `NEXT_PUBLIC_*` | Railway variable plus a Dockerfile `ARG` | Inlined at build time. A Docker build cannot see a variable unless the Dockerfile declares it with `ARG`. |
| `DATABASE_URL` | Reference variable | Set the value to `${{Postgres.DATABASE_URL}}`, where `Postgres` is the database service name. |
| `RAILWAY_DOCKERFILE_PATH` | Railway variable | Only when the Dockerfile is not named `Dockerfile` at the root of the source directory. |
| `RAILWAY_TOKEN` | CI secret | A project token for CI. Never needed in the app, never pasted into a conversation. |

## Stop and ask the human

- Any secret value. Ask for the variable to be set by the human. Never print, log, commit or echo a secret, and never ask for one to be pasted into the conversation.
- Any sign-in, account creation, plan choice or payment method.
- Anything that deletes data or cannot be undone.
- Creating or changing DNS records. Show the records and wait. Do not edit DNS, and do not suggest moving nameservers without asking.
- A `railway config plan` that lists anything to delete or destroy. Show the plan and wait.
- Running migrations against a database that already holds real data.
- Writing a new Dockerfile when one already exists.

## Steps

### 1. Add a health route

Railway polls a path you choose during each deploy and switches traffic only after a 2xx answer. The default timeout is 300 seconds. The request arrives with the hostname `healthcheck.railway.app`, so allow that host if the app filters by host. Railway does not call the path again after the deploy.

The route must not touch a database, an auth provider or any other service. Exclude it from auth middleware.

```ts
// app/api/health/route.ts
import { NextResponse } from 'next/server';

// Never cache: every health check must hit the running process.
export const dynamic = 'force-dynamic';

// No database, no auth, no upstream calls. It answers only "is the app up?".
export async function GET(): Promise<NextResponse> {
  return NextResponse.json({ status: 'ok' }, { status: 200 });
}
```

Check: start the app locally and request `/api/health`. It returns 200 with no credentials.

### 2. Make sure the image builds

Railway uses a file named exactly `Dockerfile` at the root of the source directory and prints `Using detected Dockerfile!` in the build log. If the repository has no Dockerfile, propose one and wait for approval before writing it.

The essentials for a standalone Next.js app in a pnpm monorepo, from our own image. Declare one `ARG` per build-time variable. In a monorepo, keep the build context at the repository root and do not set a root directory on the service.

```dockerfile
# Excerpt: the dependency-install stage is omitted.
FROM base AS builder
COPY --from=deps /app ./
COPY . .
# NEXT_PUBLIC_* values are inlined at build time. Declaring the ARG is what
# lets the build see the Railway variable of the same name.
ARG NEXT_PUBLIC_SITE_URL
ENV NEXT_PUBLIC_SITE_URL=${NEXT_PUBLIC_SITE_URL}
RUN pnpm exec turbo build --filter=web...

FROM base AS runner
ENV NODE_ENV=production
# Bind all interfaces, on the port the custom domain will target.
ENV PORT=3100
ENV HOSTNAME=0.0.0.0
# next.config: output: 'standalone'. Static files and public/ are copied separately.
COPY --from=builder /app/apps/web/.next/standalone ./
COPY --from=builder /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder /app/apps/web/public ./apps/web/public
EXPOSE 3100
CMD ["node", "apps/web/server.js"]
```

Check: if Docker is available, `docker build .` finishes without error.

### 3. Create or link the project, set variables, deploy

```bash
npm i -g @railway/cli     # or: brew install railway
railway login             # opens a browser; do this yourself
railway init              # new project (railway link for an existing one)
railway variable set NEXT_PUBLIC_SITE_URL=https://www.example.com
railway up                # build and deploy the current directory
railway logs              # runtime logs; add --build for the build
```

Set non-secret variables with `railway variable set KEY=value`. For each secret, give the human the name and wait while they set it in the service Variables tab. Variable changes made in the dashboard are staged and take effect only after they are deployed.

Check: `railway logs` shows the app listening and the deployment becomes active. If the health check times out, the app is not listening on the expected port or the route is behind auth.

### 4. Put the service settings in code

Railway does not read this file during a deploy. A push builds with the settings that were last applied, so run the plan whenever the file changes.

```bash
npm install railway       # the SDK the config file imports
railway config pull       # write .railway/railway.ts from the linked project
railway config plan       # preview: reads Railway, changes nothing
railway config apply      # apply, after a confirmation prompt
```

The shape of one service:

```ts
// .railway/railway.ts
import { defineRailway, github, preserve, project, service } from "railway/iac";

export default defineRailway(() => {
  const web = service("web", {
    source: github("your-org/your-repo", { checkSuites: false }),
    build: { builder: "DOCKERFILE", dockerfilePath: "Dockerfile" },
    deploy: { healthcheckPath: "/api/health", healthcheckTimeout: 30 },
    domains: ["www.example.com"],
    env: {
      NEXT_PUBLIC_SITE_URL: "https://www.example.com",
      // The name is in git. The value stays on Railway.
      SESSION_SECRET: preserve(),
    },
  });

  return project("my-app", { resources: [web] });
});
```

Check: `railway config plan` reports only the changes you intend and nothing to delete.

### 5. Add a database, if the app needs one

Add PostgreSQL with `railway add --database postgres`. Reference its `DATABASE_URL` from the app, and run migrations as a pre-deploy command, which runs after the build and before the new version starts. If it exits with an error, the deployment stops. Do not run migrations inside the Docker build.

```ts
// .railway/railway.ts (add postgres to the import from "railway/iac")
const Postgres = postgres("Postgres");

const api = service("api", {
  source: github("your-org/your-repo", { checkSuites: false }),
  build: { builder: "DOCKERFILE", dockerfilePath: "apps/api/Dockerfile" },
  deploy: {
    // Fail the deploy before it goes live if a migration breaks.
    preDeployCommand: ["pnpm --filter api db:migrate:prod"],
    healthcheckPath: "/api/v1/health",
  },
  env: { DATABASE_URL: Postgres.env.DATABASE_URL },
});
```

Check: the deployment log shows the migration command finishing before the app starts.

### 6. Get a public URL

Run `railway domain` with no arguments to generate a Railway domain, or use Generate Domain under Settings, Networking, Public Networking.

Check: `curl -i https://<generated-domain>/api/health` returns 200. Fix the app here before touching DNS.

### 7. Connect the custom domain

```bash
railway domain www.example.com          # add the custom domain
railway domain status www.example.com   # show the DNS records to create
```

Railway asks for two DNS records: a CNAME, and a TXT record that proves ownership. Both are required. With only the CNAME the domain does not verify and requests return 404. Show the human both records exactly as Railway prints them, and wait.

Tell the human these facts so they can choose:

- On Cloudflare, either keep the records DNS only, or if they are proxied set the SSL/TLS mode to Full. Railway says Full (Strict) will not work as intended.
- A root domain needs CNAME flattening or an ALIAS record. Railway lists Cloudflare, DNSimple and Namecheap as supporting it, and AWS Route 53 and GoDaddy as not supporting it.
- Custom domain limits: one on a trial, two per service on Hobby, 20 per service on Pro.

Check: `railway domain status <hostname>` shows the domain as verified, then `curl -I https://<hostname>/api/health` returns 200. Railway issues the certificate itself, usually within an hour of the DNS change.

### 8. Point the app at its real address

Update any variable that holds the public URL (for example `NEXT_PUBLIC_SITE_URL`), redeploy, and confirm the sitemap and canonical tags use the new hostname.

### If a deploy goes wrong

Read `railway logs` and `railway logs --build`. To go back, the human can open the service deployments, use the three-dot menu on an earlier deployment and choose Rollback. That restores the image and the variables. It does not undo a database migration.

## Done when

- The health route returns 200 on the custom hostname over HTTPS.
- A push to the connected branch deploys without manual steps.
- No secret value is in the repository, in the config file or in your output.
- You have given the human a list of everything you created on Railway and every variable name you set.

## Sources

- [CLI](https://docs.railway.com/cli)
- [Dockerfiles](https://docs.railway.com/builds/dockerfiles)
- [Variables](https://docs.railway.com/variables)
- [Healthchecks](https://docs.railway.com/deployments/healthchecks)
- [Pre-deploy command](https://docs.railway.com/deployments/pre-deploy-command)
- [PostgreSQL](https://docs.railway.com/databases/postgresql)
- [Infrastructure as Code](https://docs.railway.com/infrastructure-as-code)
- [Config as code reference](https://docs.railway.com/config-as-code/reference)
- [Public networking](https://docs.railway.com/networking/public-networking)
- [Working with domains](https://docs.railway.com/networking/domains/working-with-domains)
- [Deployment actions](https://docs.railway.com/deployments/deployment-actions)
- [GitHub autodeploys](https://docs.railway.com/deployments/github-autodeploys)
- [Pricing plans](https://docs.railway.com/pricing/plans)
