跳转到内容

Deploy to Fly.io

此内容尚不支持你的语言。

The repository ships a working fly.toml. This page explains what is in it and why, so you can adopt it as is or change it knowing what each part does.

  1. Create the app and pick a region:

    Terminal window
    fly launch --no-deploy

    Keep the shipped fly.toml when it asks. The sections below depend on what is in it.

  2. Set the database connection string as a secret:

    Terminal window
    fly secrets set MONGODB_URI='mongodb+srv://user:password@cluster.example.mongodb.net'

    See MongoDB Atlas for the details of the string, including why the database name does not belong in it.

    For PostgreSQL, set POSTGRES_URL instead and skip DATABASE_NAME in the next step, since the database name is part of that URL. Set one connection string, never both; see PostgreSQL.

  3. Set the keyring as a secret:

    Terminal window
    fly secrets set KEYRING="$(bun run keyring new)"

    Run it in a clone of the repository, which carries the keyring command. The keyring encrypts the secrets the server stores. The keyring below explains why it must be a secret on Fly.

  4. Set the two non-secret variables in fly.toml:

    [env]
    ISSUER = 'https://auth.example.com'
    DATABASE_NAME = 'OAuth'

    ISSUER must be the public URL browsers reach the app at, and it must be right the first time: the release command bakes it into the seeded console client’s redirect URI once. Neither value is a credential, so neither needs to be a secret.

  5. Deploy:

    Terminal window
    fly deploy --remote-only
[deploy]
release_command = "sh -c 'bun run db:setup && bun run db:migrate'"

The release command is the most important line in the file. Fly runs it on a temporary Machine with the app’s environment, once per deploy attempt, before any new Machine serves traffic, and aborts the deploy on a non-zero exit.

It has to run before the app serves because the seeds must exist for the deployment to be usable at all: without the reserved admin project and client, GET /admin/login redirects to /auth with a client_id that matches no client, and the admin console is unreachable. The first-run setup page at GET /admin still works in that state, so the failure looks like a login bug, but the cause is a missing seed. The same run provisions the TTL and unique-e-mail indexes that the collections would otherwise be created without.

The release command also stops a deploy that would break a constraint: db:setup exits non-zero when a constraint it declares is not in force, so a database whose data violates a new unique index fails the deploy instead of silently serving without it.

The release command needs the connection string, DATABASE_NAME on MongoDB, and ISSUER, which it reads for the admin client’s redirect_uri. On PostgreSQL the setup step is db:setup:pg.

db:migrate follows in the same command because the server refuses to start against a database that is behind the migrations its release declares. Without db:migrate, a release that declares a migration deploys an image that cannot boot. With it, the deploy goes ahead only if the migration succeeds. Most releases declare none, and the step reports current and exits. But 0.7.0, 0.8.0, 0.10.0, 0.11.0 and 1.0.0 each carried migrations that cannot be undone, so read the release notes before a deploy and take a backup when they name one. The sh -c wrapper makes && a shell operator instead of two more arguments to bun.

The server encrypts the secrets it stores, such as application secrets and private signing keys, with a keyring that you hold outside the database. The keyring covers what it encrypts, how to rotate it and what to do if a key is lost.

On Fly, supply the keyring as the KEYRING secret, as step 3 above does. A secrets manager that syncs into Fly works as well, for example Infisical’s Fly.io secret sync. Do not rely on first-run setup to keep a keyring here. The shipped fly.toml attaches no volume, so a file written to a Machine’s disk would be gone after the next deploy. Setup sees that there is no keyring directory, so it only shows you the keyring it generated and asks you to set it as the KEYRING secret and restart.

Keep a copy of the keyring apart from your database backups. The secrets in a backup cannot be read without it.

[[http_service.checks]]
method = 'GET'
path = '/health'
interval = '30s'
timeout = '5s'
grace_period = '15s'
headers = { X-Forwarded-Proto = 'https' }
[[http_service.checks]]
method = 'GET'
path = '/ready'
interval = '60s'
timeout = '10s'
grace_period = '20s'
headers = { X-Forwarded-Proto = 'https' }

At boot the server connects to the database and loads the keystore at module scope, so a Machine that cannot reach the datastore exits instead of serving. Without a check the proxy cannot tell such a Machine from a healthy one and routes to it anyway.

Two details are there on purpose. The X-Forwarded-Proto = 'https' header is a documented safeguard against force_https turning the check into a 301 that the proxy reads as a failure. And the 15-second grace period covers a cold start, since auto_start_machines starts stopped Machines.

GET /health is the only route the rate limiter never counts, because a refused liveness probe would take the Machine out of the load balancer. It answers for the process alone, which is why the second check exists. GET /ready reports whether the datastore is reachable. Fly’s checks stop routing to a failing Machine without restarting it, so a Machine whose database has gone away is taken out of rotation instead of restarted. The /ready interval is the longer of the two on purpose: there is little to gain from asking twice a minute about something a deploy cannot fix. Load is not the concern, since the endpoint holds its last answer for a second and shares one outstanding probe, so it cannot become database load.

Fly’s proxy sits in front of the app, so every request arrives from it, from a private address. Set clientAddress.source to fly. The server then reads Fly-Client-IP, which Fly’s edge overwrites with the real caller, so a caller cannot choose its own address.

The default, automatic, is wrong on Fly. Fly appends the app’s own public address as the last entry of X-Forwarded-For, so automatic would count every caller as that one address and refuse them all together. An instance upgraded from a release before this setting existed is moved to fly by the migration; a new one needs the setting once, in Settings → Sign-in & abuse. The card under the setting shows the address the server sees for you, and warns if Fly’s header is present under any other choice.

A project can be served on a subdomain of the instance, https://acme.auth.example.com for an instance at auth.example.com. Project addresses explains the address form. On Fly.io it needs a wildcard certificate and two kinds of DNS record, added once per app:

  1. Add the wildcard certificate. Quote the name, so the shell does not expand the *:

    Terminal window
    fly certs add "*.auth.example.com"
  2. Create the validation record. Fly issues a wildcard certificate only through the DNS-01 challenge, which needs a CNAME record named _acme-challenge.auth.example.com. Its target is unique to your app. Fly shows the exact record when you run the command; fly certs setup "*.auth.example.com" shows it again. Copy it from there rather than guessing it.

  3. Point the wildcard name at the app. Add *.auth.example.com with the same A and AAAA addresses as auth.example.com, or as a CNAME to the app’s target. Fly shows the records it expects in the dashboard and in the output of fly certs add.

  4. Check it. fly certs check "*.auth.example.com" runs the validation and reports what is still missing.

Then turn on projects.addressForms. Fly’s proxy passes the original Host through, so nothing else changes in fly.toml. Each Fly app needs its own wildcard: a second instance at conformance.example.com needs *.conformance.example.com.

Fly’s own page on this is Custom domains.

Port, HTTPS, Machine stopping, deploy strategy and VM size

Section titled “Port, HTTPS, Machine stopping, deploy strategy and VM size”
  • internal_port = 3000 matches the EXPOSE 3000 in the Dockerfile and the port bun start listens on.
  • force_https = true, so ISSUER is an https URL and HSTS (which the server emits unconditionally) is not a lie.
  • auto_stop_machines = 'off' with auto_start_machines = true: the proxy never stops a Machine for want of traffic, so a request after a quiet night is served by a running process instead of waiting for a boot. min_machines_running is left out on purpose, since it only means anything while something is allowed to stop Machines. Autostart stays on as a backstop: a Machine stopped by a host event comes back on the next request. A deployment nobody depends on yet will probably want the opposite, which is what the second configuration below does.
  • strategy = 'bluegreen': with a single Machine a rolling deploy replaces it in place, so every deploy costs a boot’s worth of downtime. Blue-green boots the replacement alongside it and moves traffic once the new Machine’s checks pass. It is available only because nothing here has a volume attached; blue-green and canary both refuse one.
  • One shared-CPU VM with 1 GB of memory. Rate-limit counting is per instance and held in memory, so scaling to N Machines multiplies the effective allowance by N. The caveat in Kubernetes applies to Fly in the same way.

The repository also ships fly.conformance.toml, which describes a separate Fly app: the instance the OpenID conformance suite is pointed at. It is the same file with two choices reversed: auto_stop_machines = 'stop' and min_machines_running = 0, so it costs close to nothing between runs, and no blue-green strategy, because a test bed can afford a boot’s downtime.

Deploy it with fly deploy --remote-only -c fly.conformance.toml --ha=false. --ha=false matters because on the first deploy of a new app flyctl creates a second Machine for high availability whatever the config says. It then advises setting min_machines_running = 0, which this file already does: the two settings are unrelated. Without the flag, the test bed runs two Machines whose in-memory rate-limit counters are independent, so the effective allowance is double the configured one.

Two of its choices are probably worth borrowing for any second environment. It sets a different DATABASE_NAME, so a run cannot write into production data and its console can be configured however a test plan requires. Server settings are stored per database, so sharing a database would mean sharing them. And it stops instead of suspending, though suspending resumes faster: the server connects to the datastore and loads the keystore at module scope during boot, so a resumed process holds a connection pool it established before it was frozen, and the failure looks like a server defect instead of a cold start.