Skip to content

Commit 3624bb3

Browse files
authored
fix(cli): skip docker's first health check wait (CLI-2901) (#7430)
## TL;DR fixes `supabase start` sitting about 10s on docker's first health check when the services are already up. ## whats improved/fixed? docker runs a container's first health check one full interval after it starts, and our interval is 10s. so `supabase start` kept waiting on that check even when everything was ready sooner. a restart with the issue's excludes went from about 12.8s to 5.2s. a full stack restart went from about 14s to 8s `db start` and `db reset` get the same. ## how? containers with a docker healthcheck now get `--health-start-interval 1s` and a 10s start period when `docker version` shows API 1.44 or newer for the client binary, the client in use, and the daemon, so the first check runs about 1s in and the interval stays 10s after. kong's check lived only in its image, so its spec now sets the same `kong health` check and gets those flags too. > [!NOTE] > on engines without the flag (docker below API 1.44, podman) containers keep the 10s first check. ## ref: - closes: #7427
1 parent 0c35ecb commit 3624bb3

19 files changed

Lines changed: 335 additions & 27 deletions

‎apps/cli/src/command-internal/container-cli.ts‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -307,28 +307,42 @@ function isDockerApiVersionAtLeast(version: string, minVersion: string): boolean
307307
* fall back to Podman, whose `volume prune` has no `--all` flag to gate.
308308
*/
309309
export const dockerSupportsVolumePruneAllFlag = (spawner: Spawner) =>
310+
dockerApiVersionsSatisfy(spawner, (version) => isDockerApiVersionAtLeast(version, "1.42"));
311+
312+
/**
313+
* `docker create --health-start-interval` needs API >= 1.44 on both ends and is a hard failure
314+
* below that. The Podman CLI rejects the flag, and a `docker` shim for it fails this format or
315+
* prints Podman's own `6.x`, so a major other than 1 is not Docker's API. The real `docker` client
316+
* on a Podman socket reporting 1.44 passes: Podman keeps the start period and drops the start
317+
* interval.
318+
*/
319+
export const dockerSupportsHealthStartInterval = (spawner: Spawner) =>
320+
dockerApiVersionsSatisfy(
321+
spawner,
322+
(version) => version.startsWith("1.") && isDockerApiVersionAtLeast(version, "1.44"),
323+
);
324+
325+
/* Reads the client's own and effective API versions and the daemon's, `false` on any failure.
326+
`DOCKER_API_VERSION` can lift the effective one past what the client binary supports. */
327+
const dockerApiVersionsSatisfy = (spawner: Spawner, supported: (version: string) => boolean) =>
310328
Effect.scoped(
311329
Effect.gen(function* () {
312-
const child = yield* spawner.spawn(
313-
ChildProcess.make(
314-
"docker",
315-
["version", "--format", "{{.Client.APIVersion}} {{.Server.APIVersion}}"],
316-
{
317-
stdin: "ignore",
318-
stdout: "pipe",
319-
stderr: "ignore",
320-
},
321-
),
330+
const child = yield* spawnRuntime(
331+
spawner,
332+
"docker",
333+
[
334+
"version",
335+
"--format",
336+
"{{.Client.DefaultAPIVersion}} {{.Client.APIVersion}} {{.Server.APIVersion}}",
337+
],
338+
{ stdin: "ignore", stdout: "pipe", stderr: "ignore" },
322339
);
323340
const [exitCode, stdout] = yield* Effect.all(
324341
[child.exitCode.pipe(Effect.map(Number)), collectText(child.stdout)],
325342
{ concurrency: "unbounded" },
326343
);
327344
if (exitCode !== 0) return false;
328345
const versions = stdout.trim().split(/\s+/);
329-
return (
330-
versions.length === 2 &&
331-
versions.every((version) => isDockerApiVersionAtLeast(version, "1.42"))
332-
);
346+
return versions.length === 3 && versions.every(supported);
333347
}),
334348
).pipe(Effect.orElseSucceed(() => false));

‎apps/cli/src/command-internal/container-cli.unit.test.ts‎

Lines changed: 68 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
containerCliExitCode,
77
containerRuntimeNotFoundMessage,
88
describeContainerCliFailure,
9+
dockerSupportsHealthStartInterval,
910
dockerSupportsVolumePruneAllFlag,
1011
isContainerNotFoundMessage,
1112
spawnContainerCli,
@@ -17,7 +18,11 @@ function mockSpawner(
1718
readonly bothMissing?: boolean;
1819
readonly exitCode?: number;
1920
readonly stdout?: string;
20-
readonly apiVersions?: { readonly client: string; readonly server: string };
21+
readonly apiVersions?: {
22+
readonly clientDefault?: string;
23+
readonly client: string;
24+
readonly server: string;
25+
};
2126
} = {},
2227
) {
2328
const spawned: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> = [];
@@ -40,6 +45,10 @@ function mockSpawner(
4045
const stdout =
4146
opts.apiVersions !== undefined && args[0] === "version"
4247
? (args[args.indexOf("--format") + 1] ?? "")
48+
.replaceAll(
49+
"{{.Client.DefaultAPIVersion}}",
50+
opts.apiVersions.clientDefault ?? opts.apiVersions.client,
51+
)
4352
.replaceAll("{{.Client.APIVersion}}", opts.apiVersions.client)
4453
.replaceAll("{{.Server.APIVersion}}", opts.apiVersions.server)
4554
: opts.stdout;
@@ -229,6 +238,57 @@ describe("container CLI process spans", () => {
229238
);
230239
});
231240

241+
describe("dockerSupportsHealthStartInterval", () => {
242+
it.live.each([
243+
{ name: "both ends at the 1.44 minimum", client: "1.44", server: "1.44" },
244+
{ name: "a new client against a newer daemon", client: "1.47", server: "1.56" },
245+
{ name: "a three-part API version", client: "1.44.0", server: "1.44.0" },
246+
])("returns true for $name", ({ client, server }) => {
247+
const mock = mockSpawner({ apiVersions: { client, server } });
248+
return dockerSupportsHealthStartInterval(mock.spawner).pipe(
249+
Effect.map((supported) => {
250+
expect(supported).toBe(true);
251+
}),
252+
);
253+
});
254+
255+
it.live.each([
256+
{
257+
name: "a client below API 1.44",
258+
options: { apiVersions: { client: "1.43", server: "1.56" } },
259+
},
260+
{
261+
name: "an old client with DOCKER_API_VERSION forced up",
262+
options: { apiVersions: { clientDefault: "1.43", client: "1.44", server: "1.56" } },
263+
},
264+
{
265+
name: "a daemon below API 1.44",
266+
options: { apiVersions: { client: "1.56", server: "1.43" } },
267+
},
268+
{
269+
name: "a docker shim printing Podman's own version",
270+
options: { apiVersions: { client: "6.1.3", server: "6.1.3" } },
271+
},
272+
{
273+
name: "a shim whose major starts with a 1",
274+
options: { apiVersions: { client: "10.1.0", server: "10.1.0" } },
275+
},
276+
{ name: "fewer than three versions", options: { stdout: "1.56 1.56" } },
277+
{
278+
name: "the version command exiting non-zero",
279+
options: { exitCode: 1, stdout: "1.56 1.56 1.56" },
280+
},
281+
{ name: "docker not being installed", options: { dockerMissing: true } },
282+
])("returns false for $name", ({ options }) => {
283+
const mock = mockSpawner(options);
284+
return dockerSupportsHealthStartInterval(mock.spawner).pipe(
285+
Effect.map((supported) => {
286+
expect(supported).toBe(false);
287+
}),
288+
);
289+
});
290+
});
291+
232292
describe("dockerSupportsVolumePruneAllFlag", () => {
233293
it.live(
234294
"returns true when the client and daemon both report an API version at or above 1.42",
@@ -240,7 +300,11 @@ describe("dockerSupportsVolumePruneAllFlag", () => {
240300
expect(mock.spawned).toEqual([
241301
{
242302
command: "docker",
243-
args: ["version", "--format", "{{.Client.APIVersion}} {{.Server.APIVersion}}"],
303+
args: [
304+
"version",
305+
"--format",
306+
"{{.Client.DefaultAPIVersion}} {{.Client.APIVersion}} {{.Server.APIVersion}}",
307+
],
244308
},
245309
]);
246310
}),
@@ -266,8 +330,8 @@ describe("dockerSupportsVolumePruneAllFlag", () => {
266330
name: "versions that only compare above 1.42 lexicographically",
267331
options: { apiVersions: { client: "1.9", server: "1.9" } },
268332
},
269-
{ name: "a single version instead of a client and daemon pair", options: { stdout: "1.51" } },
270-
{ name: "more than two versions", options: { stdout: "1.51 1.51 1.51" } },
333+
{ name: "a single version", options: { stdout: "1.51" } },
334+
{ name: "more than three versions", options: { stdout: "1.51 1.51 1.51 1.51" } },
271335
{ name: "empty output", options: { stdout: "" } },
272336
])("returns false for $name", ({ options }) => {
273337
const mock = mockSpawner(options);

‎apps/cli/src/command-internal/db-bootstrap/container-lifecycle.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import {
3434
import {
3535
buildStartContainerCreateArgs,
3636
applyBitbucketStartContainerFilter,
37+
applyHealthStartInterval,
3738
isDockerClientEnvKey,
3839
type StartContainerSpec,
3940
} from "./docker-create-args.ts";
@@ -124,6 +125,11 @@ export interface ContainerOpts {
124125
readonly projectId: string;
125126
/** Passed in (rather than read via env here) so this module stays a pure effect orchestrator. */
126127
readonly isBitbucketPipeline: boolean;
128+
/**
129+
* Whether the engine takes `--health-start-interval`, probed once per run by each command that
130+
* reads Docker's health status. Shadow databases leave it unset: nothing reads theirs.
131+
*/
132+
readonly healthStartInterval?: boolean;
127133
/**
128134
* Stamped onto every created container as {@link CLI_WORKDIR_LABEL} so a later `stop` or
129135
* {@link rollbackStart} can find this directory from the container's own label alone, without
@@ -716,7 +722,10 @@ export function createContainer(
716722
}
717723
}
718724

719-
const finalSpec = applyBitbucketStartContainerFilter(labeledSpec, opts.isBitbucketPipeline);
725+
const finalSpec = applyHealthStartInterval(
726+
applyBitbucketStartContainerFilter(labeledSpec, opts.isBitbucketPipeline),
727+
opts.healthStartInterval === true,
728+
);
720729

721730
const createArgs = buildStartContainerCreateArgs(finalSpec);
722731
// `isDockerClientEnvKey` keys are already emitted inline as `-e KEY=value` above; see

‎apps/cli/src/command-internal/db-bootstrap/container-lifecycle.unit.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,65 @@ describe("createContainer", () => {
297297
);
298298
});
299299

300+
describe("Docker's first health check", () => {
301+
const steady = { test: ["CMD", "true"], intervalSeconds: 10, timeoutSeconds: 2, retries: 3 };
302+
const steadyFlags = {
303+
"--health-cmd": "true",
304+
"--health-interval": "10s",
305+
"--health-timeout": "2s",
306+
"--health-retries": "3",
307+
};
308+
const startFlags = { "--health-start-period": "10s", "--health-start-interval": "1s" };
309+
310+
it.live.each([
311+
{
312+
name: "adds start flags where the engine takes them",
313+
healthcheck: steady,
314+
supported: true,
315+
expected: { ...steadyFlags, ...startFlags },
316+
},
317+
{
318+
name: "keeps a service's own start period",
319+
healthcheck: { ...steady, startPeriodSeconds: 20 },
320+
supported: true,
321+
expected: { ...steadyFlags, ...startFlags, "--health-start-period": "20s" },
322+
},
323+
{
324+
name: "adds none where the engine rejects them",
325+
healthcheck: steady,
326+
supported: false,
327+
expected: steadyFlags,
328+
},
329+
{
330+
name: "adds none for a caller that never asked",
331+
healthcheck: steady,
332+
expected: steadyFlags,
333+
},
334+
{ name: "adds none without a healthcheck", supported: true, expected: {} },
335+
])("$name", ({ healthcheck, supported, expected }) => {
336+
const mock = alwaysSucceed();
337+
return createContainer(
338+
mock.spawner,
339+
{ ...baseSpec, binds: [], ...(healthcheck === undefined ? {} : { healthcheck }) },
340+
{
341+
projectId: "proj",
342+
isBitbucketPipeline: false,
343+
workdir: workdir.current,
344+
extraHosts: [],
345+
...(supported === undefined ? {} : { healthStartInterval: supported }),
346+
},
347+
).pipe(
348+
Effect.map(() => {
349+
const args = mock.spawned.find((spawned) => spawned[0] === "create") ?? [];
350+
const flags = args.flatMap((arg, index) =>
351+
arg.startsWith("--health-") ? [[arg, args[index + 1]]] : [],
352+
);
353+
expect(Object.fromEntries(flags)).toEqual(expected);
354+
}),
355+
);
356+
});
357+
});
358+
300359
it.live("fails with ContainerStartError, unmodified, on a plain start failure", () => {
301360
const mock = mockSpawner((args) => {
302361
if (args[0] === "create") return { exitCode: 0, stdout: "abc\n" };

‎apps/cli/src/command-internal/db-bootstrap/docker-create-args.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@ interface StartHealthcheckSpec {
2323
readonly retries?: number;
2424
/** Emitted as `--health-start-period <n>s`; omitted when unset. */
2525
readonly startPeriodSeconds?: number;
26+
/** Emitted as `--health-start-interval <n>s`; see {@link applyHealthStartInterval}. */
27+
readonly startIntervalSeconds?: number;
2628
}
2729

2830
/** One `-p <hostPort>:<containerPort>[/<protocol>]` entry. */
@@ -203,6 +205,12 @@ function buildHealthcheckArgs(healthcheck: StartHealthcheckSpec): ReadonlyArray<
203205
if (healthcheck.startPeriodSeconds !== undefined) {
204206
args.push("--health-start-period", formatDockerDurationSeconds(healthcheck.startPeriodSeconds));
205207
}
208+
if (healthcheck.startIntervalSeconds !== undefined) {
209+
args.push(
210+
"--health-start-interval",
211+
formatDockerDurationSeconds(healthcheck.startIntervalSeconds),
212+
);
213+
}
206214
return args;
207215
}
208216

@@ -288,3 +296,26 @@ export function applyBitbucketStartContainerFilter(
288296
securityOpt: [],
289297
};
290298
}
299+
300+
/* Docker returns to `--health-interval` after the first pass or the end of the start period. */
301+
const HEALTH_START_INTERVAL_SECONDS = 1;
302+
/* The start interval only runs inside a start period, whose failures do not count. One steady
303+
interval keeps `unhealthy` where it was, or one interval later if a slow probe straddles it. */
304+
const HEALTH_START_PERIOD_SECONDS = 10;
305+
306+
/* Runs a container's first health checks right after it starts instead of a full interval later.
307+
`supported` comes from `dockerSupportsHealthStartInterval`; without it the spec is unchanged. */
308+
export function applyHealthStartInterval(
309+
spec: StartContainerSpec,
310+
supported: boolean,
311+
): StartContainerSpec {
312+
if (!supported || spec.healthcheck === undefined) return spec;
313+
return {
314+
...spec,
315+
healthcheck: {
316+
...spec.healthcheck,
317+
startPeriodSeconds: spec.healthcheck.startPeriodSeconds ?? HEALTH_START_PERIOD_SECONDS,
318+
startIntervalSeconds: HEALTH_START_INTERVAL_SECONDS,
319+
},
320+
};
321+
}

‎apps/cli/src/command-internal/db-bootstrap/recreate-local-database.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import {
2323
ErrorActionabilityId,
2424
} from "../../shared/telemetry/error-actionability.ts";
2525
import { isSqlState } from "../connect-errors.ts";
26-
import { isContainerNotFoundMessage } from "../container-cli.ts";
26+
import { dockerSupportsHealthStartInterval, isContainerNotFoundMessage } from "../container-cli.ts";
2727
import { checkDbToml } from "../db-config.toml-read.ts";
2828
import { DbConnection, type DbSession } from "../db-connection.service.ts";
2929
import { DbExecError, type DbConnectError } from "../db-connection.errors.ts";
@@ -292,7 +292,10 @@ const recreateLocalDatabase15 = <E>(
292292
...input.postgresSpec,
293293
image: resolvedPostgresImage,
294294
});
295-
yield* createContainer(spawner, postgresSpec, input.containerOpts);
295+
yield* createContainer(spawner, postgresSpec, {
296+
...input.containerOpts,
297+
healthStartInterval: yield* dockerSupportsHealthStartInterval(spawner),
298+
});
296299

297300
// Never swallowed — reset has no `--from-backup`-equivalent gate.
298301
yield* waitForPostgresReady(

‎apps/cli/src/command-internal/db-bootstrap/start-local-database.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { parseUrl } from "../storage-url.ts";
2828
import { loadLocalProjectContext } from "../local-project-context.ts";
2929
import { cliProjectFilterValue, localDbContainerId } from "../docker-ids.ts";
3030
import { isBitbucketPipeline } from "../bitbucket-pipeline.ts";
31+
import { dockerSupportsHealthStartInterval } from "../container-cli.ts";
3132
import { holdProjectLifecycleLock } from "../project-lifecycle-lock.ts";
3233
import { dbNotRunningError } from "../status-errors.ts";
3334
import { buildLocalDbContainerInputs } from "./local-container-inputs.ts";
@@ -267,7 +268,10 @@ const startLocalDatabaseInScope = Effect.fn("DbBootstrap.startLocalDatabase")(fu
267268
hostname,
268269
dbContainerId,
269270
dbPort: values.dbPort,
270-
containerOpts,
271+
containerOpts: {
272+
...containerOpts,
273+
healthStartInterval: yield* dockerSupportsHealthStartInterval(spawner),
274+
},
271275
// `db reset` has no `fromBackup` concept at all, so `postgresSpecBase` omits it.
272276
postgresSpec: { ...postgresSpecBase, fromBackup },
273277
// Only the `db` container's own image, resolved lazily, right where it would be

‎apps/cli/src/commands/db/reset/SIDE_EFFECTS.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ equivalent, PG15) or `InitSchema14`/`ApplyApiPrivileges` (PG14).
100100
| `docker container inspect supabase_db_<project>` | local path | `AssertSupabaseDbIsRunning` probe (Podman fallback) — spawned only when the direct Engine-API request over the active local socket/named pipe gives no definitive answer |
101101
| `docker stop <storage\|auth\|realtime\|pooler container>` | local path, PG15 | stop the satellites before removing the db container so their `unless-stopped` restarts cannot race the one-shot init jobs (issue #6915), not-found tolerated per service |
102102
| `docker container rm -f supabase_db_<project>` / `docker volume rm -f <same>` | local path, PG15 | remove the existing container/volume before recreating (Podman fallback) |
103+
| `docker version --format ...` | local path, PG15 | once before `docker create`: API >= 1.44 on both ends adds the health start flags (see below) |
103104
| `docker network create` / `docker volume create` / `docker create` / `docker start` | local path, PG15 | recreate the Postgres container (same primitives `db start` uses) |
104105
| `docker run --rm <realtime\|storage\|gotrue image>` | local path, PG15, per enabled service | the one-shot `initSchema15` migrate jobs (`startSetupLocalDatabase`) |
105106
| `docker restart <db container>` | local path, PG14 | `RestartDatabase` — pg_cron must restart after `pg_terminate_backend` |
@@ -115,7 +116,10 @@ published Postgres address (2s dial cap). Before the command returns, it waits u
115116
Docker's first health verdict on the database container (polling `docker container inspect` every
116117
1s until the status leaves `starting`, the container stops running, or Docker cannot launch its
117118
health check), so a following `supabase status` does not see `starting`. That wait never fails the
118-
reset.
119+
reset. When `docker version` reports API >= 1.44 on both ends, `docker create` also gets
120+
`--health-start-period 10s --health-start-interval 1s`, so its first check runs about 1s after start
121+
instead of 10s. Older engines and the Podman CLI get neither flag; the `docker` client on a Podman
122+
socket reporting API >= 1.44 gets both, Podman drops the interval, and there is no speedup.
119123

120124
No subprocess delegation on either target — the remote path's
121125
`--experimental` schema-files apply is fully native.

‎apps/cli/src/commands/db/reset/reset.integration.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1208,6 +1208,20 @@ describe("db reset", () => {
12081208
);
12091209
});
12101210

1211+
it.effect("emits the health-start flags on a supported engine", () => {
1212+
const base = defaultLocalResetRoute();
1213+
const { layer, child } = setup(tmp.current, {
1214+
toml: 'project_id = "test"\n',
1215+
args: ["db", "reset"],
1216+
isLocal: true,
1217+
route: (args) => (args[0] === "version" ? { stdout: ["1.44 1.44 1.56"] } : base(args)),
1218+
});
1219+
return Effect.gen(function* () {
1220+
yield* dbReset(DEFAULT_FLAGS).pipe(Effect.provide(layer));
1221+
expect(createArgs(child.spawned)).toContain("--health-start-interval");
1222+
});
1223+
});
1224+
12111225
it.effect(
12121226
"recreates when Docker cannot exec the database's health check but it accepts connections",
12131227
() => {

0 commit comments

Comments
 (0)