feat: add start/stop/restart controls and explain build vs deploy in the panel

Start/stop/restart act on the existing container instead of recreating it.
Docker's 304 (already started/stopped) is treated as success.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-19 05:26:22 +02:00
1 parent 0d38b3950c
commit a999b8c694
8 files changed
+222

No files matched your search

+21
View File
@@ -13,6 +13,9 @@ import {
buildInstallation,
deployInstallation,
redeployInstallation,
startInstallation,
stopInstallation,
restartInstallation,
removeInstallationContainer,
} from "../service/orchestrator.js";
import { buildLogPath } from "../build/nixpacks.js";
@@ -117,6 +120,24 @@ installationsRouter.post("/:id/redeploy", async (req, res) => {
}
});
for (const [action, handler] of [
["start", startInstallation],
["stop", stopInstallation],
["restart", restartInstallation],
] as const) {
installationsRouter.post(`/:id/${action}`, async (req, res) => {
if (!getInstallationById(req.params.id)) {
res.status(404).json({ error: "not found" });
return;
}
try {
res.json(toPublicJson(await handler(req.params.id)));
} catch (err) {
res.status(500).json({ error: (err as Error).message });
}
});
}
installationsRouter.get("/:id/logs", (req, res) => {
const installation = getInstallationById(req.params.id);
if (!installation) {
+36
View File
@@ -3,6 +3,7 @@ import Docker from "dockerode";
import { config } from "../config/env.js";
import type { Installation } from "../db/installations.js";
import { withTimeout } from "../util/withTimeout.js";
import { isNotFoundError, isNotModifiedError } from "./errors.js";
const docker = new Docker({ socketPath: config.dockerSocketPath });
@@ -18,6 +19,8 @@ export async function ensureNetwork(name: string): Promise<void> {
// cache plus a call timeout keeps one wedged Docker daemon from snowballing into the proxy.
const IP_CACHE_TTL_MS = 5_000;
const DOCKER_CALL_TIMEOUT_MS = 10_000;
// stop/restart send SIGTERM and wait the daemon's grace period (10s) before SIGKILL.
const DOCKER_STOP_TIMEOUT_MS = 30_000;
const ipCache = new Map<string, { ip: Promise<string>; expires: number }>();
export async function removeContainerIfExists(containerName: string): Promise<void> {
@@ -99,6 +102,39 @@ export async function stopInstallationContainer(containerName: string): Promise<
await removeContainerIfExists(containerName);
}
// Lifecycle actions on the EXISTING container (no remove/recreate, so the image and the
// config it was created with stay untouched). Resolves false when the container no longer
// exists, so the caller can fall back to a full deploy. The container's IP can change across a
// stop/start, hence the cache is dropped before and after.
async function actOnExistingContainer(
containerName: string,
what: string,
timeoutMs: number,
action: (container: Docker.Container) => Promise<unknown>,
): Promise<boolean> {
ipCache.delete(containerName);
try {
await withTimeout(action(docker.getContainer(containerName)), timeoutMs, `docker ${what} ${containerName}`);
return true;
} catch (err) {
if (isNotFoundError(err)) return false;
// start on a running container / stop on a stopped one: already where we want it.
if (isNotModifiedError(err)) return true;
throw err;
} finally {
ipCache.delete(containerName);
}
}
export const stopContainer = (containerName: string) =>
actOnExistingContainer(containerName, "stop", DOCKER_STOP_TIMEOUT_MS, (c) => c.stop());
export const startContainer = (containerName: string) =>
actOnExistingContainer(containerName, "start", DOCKER_CALL_TIMEOUT_MS, (c) => c.start());
export const restartContainer = (containerName: string) =>
actOnExistingContainer(containerName, "restart", DOCKER_STOP_TIMEOUT_MS, (c) => c.restart());
async function lookupContainerIp(containerName: string): Promise<string> {
const info = await withTimeout(
docker.getContainer(containerName).inspect(),
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from "vitest";
import { isNotFoundError, isNotModifiedError } from "./errors.js";
describe("isNotFoundError", () => {
it("matches a Docker API 404", () => {
expect(isNotFoundError(Object.assign(new Error("no such container"), { statusCode: 404 }))).toBe(true);
});
it("does not match other Docker errors or non-errors", () => {
expect(isNotFoundError(Object.assign(new Error("server error"), { statusCode: 500 }))).toBe(false);
expect(isNotFoundError(new Error("docker inspect x timed out after 10000ms"))).toBe(false);
expect(isNotFoundError(undefined)).toBe(false);
expect(isNotFoundError("404")).toBe(false);
});
});
describe("isNotModifiedError", () => {
it("matches the 304 docker-modem raises for already started/stopped containers", () => {
expect(isNotModifiedError(Object.assign(new Error("already started"), { statusCode: 304 }))).toBe(true);
expect(isNotModifiedError(Object.assign(new Error("boom"), { statusCode: 500 }))).toBe(false);
expect(isNotModifiedError(new Error("plain"))).toBe(false);
});
});
+9
View File
@@ -0,0 +1,9 @@
/** True when a dockerode call failed because the target container (or image) doesn't exist. */
export function isNotFoundError(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { statusCode?: unknown }).statusCode === 404;
}
/** True for HTTP 304: docker-modem surfaces "already started/stopped" as an error, but it means the container is already in the wanted state. */
export function isNotModifiedError(err: unknown): boolean {
return typeof err === "object" && err !== null && (err as { statusCode?: unknown }).statusCode === 304;
}
+49
View File
@@ -12,6 +12,9 @@ import { runNixpacksBuild } from "../build/nixpacks.js";
import {
runInstallationContainer,
stopInstallationContainer,
stopContainer,
startContainer,
restartContainer,
waitForContainerHealth,
getImageId,
removeImageIfUnused,
@@ -144,6 +147,52 @@ export async function redeployInstallation(id: string, opts: { rebuild?: boolean
return deployInstallation(id);
}
// Start/restart act on the existing container, so they never apply changed env/config (that
// needs a deploy, which recreates it). If the container is gone (e.g. pruned after a host
// reboot) they fall back to a deploy from the built image.
async function resumeInstallation(
id: string,
act: (containerName: string) => Promise<boolean>,
): Promise<Installation> {
const installation = getInstallationById(id);
if (!installation) throw new Error("installation not found");
updateInstallation(id, { status: "starting", statusDetail: null });
try {
if (!(await act(installation.containerName))) {
if (!installation.imageTag) {
throw new Error("container does not exist and the installation has no built image — build it first");
}
return await deployInstallation(id);
}
await waitForContainerHealth(installation);
const bearerToken = installation.bearerToken ?? generateBearerToken();
return updateInstallation(id, { status: "running", statusDetail: null, bearerToken });
} catch (err) {
return updateInstallation(id, { status: "error", statusDetail: (err as Error).message });
}
}
export const startInstallation = (id: string) => resumeInstallation(id, startContainer);
export const restartInstallation = (id: string) => resumeInstallation(id, restartContainer);
/** Stops the container without removing it; it stays stopped (restart policy `unless-stopped`) until started again. */
export async function stopInstallation(id: string): Promise<Installation> {
const installation = getInstallationById(id);
if (!installation) throw new Error("installation not found");
try {
// A missing container is already stopped as far as the operator is concerned.
await stopContainer(installation.containerName);
return updateInstallation(id, { status: "stopped", statusDetail: null });
} catch (err) {
return updateInstallation(id, { status: "error", statusDetail: (err as Error).message });
}
}
export async function removeInstallationContainer(id: string): Promise<void> {
const installation = getInstallationById(id);
if (!installation) return;
+3
View File
@@ -53,6 +53,9 @@ export const api = {
deploy: (id: string) => request<Installation>(`/api/installations/${id}/deploy`, { method: "POST" }),
redeploy: (id: string, rebuild: boolean) =>
request<Installation>(`/api/installations/${id}/redeploy`, { method: "POST", body: JSON.stringify({ rebuild }) }),
start: (id: string) => request<Installation>(`/api/installations/${id}/start`, { method: "POST" }),
stop: (id: string) => request<Installation>(`/api/installations/${id}/stop`, { method: "POST" }),
restart: (id: string) => request<Installation>(`/api/installations/${id}/restart`, { method: "POST" }),
regenerateToken: (id: string) =>
request<{ bearerToken: string }>(`/api/installations/${id}/regenerate-token`, { method: "POST" }),
remove: (id: string) => request<void>(`/api/installations/${id}`, { method: "DELETE" }),
+60
View File
@@ -91,6 +91,11 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
}
const deployLocked = DEPLOY_LOCKED_STATUSES.has(installation.status);
const isRunning = installation.status === "running";
// Start also covers "built"/"error" with an image: with no container yet it falls back to a deploy.
const canStart =
installation.status === "stopped" ||
((installation.status === "built" || installation.status === "error") && installation.imageTag !== null);
return (
<Shell title={installation.name} onLoggedOut={onLoggedOut}>
@@ -232,6 +237,54 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
<button
type="button"
className="btn"
title="Start the stopped container as it is. If it no longer exists, deploys it from the built image."
disabled={busy !== null || deployLocked || !canStart}
onClick={() =>
withBusy("start", async () => {
await api.start(installation.id);
await refresh();
})
}
>
{busy === "start" ? "Starting…" : "Start"}
</button>
<button
type="button"
className="btn"
title="Stop the container without removing it. It stays stopped until you start it again."
disabled={busy !== null || deployLocked || !isRunning}
onClick={() =>
withBusy("stop", async () => {
await api.stop(installation.id);
await refresh();
})
}
>
{busy === "stop" ? "Stopping…" : "Stop"}
</button>
<button
type="button"
className="btn"
title="Restart the running container in place. Does not apply changed environment variables; use Deploy for that."
disabled={busy !== null || deployLocked || !isRunning}
onClick={() =>
withBusy("restart", async () => {
await api.restart(installation.id);
await refresh();
})
}
>
{busy === "restart" ? "Restarting…" : "Restart"}
</button>
</div>
<p className="card-hint" style={{ margin: "8px 0 16px" }}>
Start, Stop and Restart act on the existing container: fast, and the image and its configuration stay as they are.
</p>
<div className="actions-row">
<button
type="button"
className="btn"
title="Re-clone the repository and build a new image with Nixpacks. Does not touch the running container."
disabled={busy !== null}
onClick={() =>
withBusy("build", async () => {
@@ -245,6 +298,7 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
<button
type="button"
className="btn"
title="Create and start a new container from the built image, replacing any existing one. Applies changed environment variables."
disabled={busy !== null || deployLocked}
onClick={() =>
withBusy("deploy", async () => {
@@ -258,6 +312,7 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
<button
type="button"
className="btn"
title="Deploy again from the current image, without rebuilding. Applies changed environment variables."
disabled={busy !== null}
onClick={() =>
withBusy("redeploy", async () => {
@@ -271,6 +326,7 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
<button
type="button"
className="btn"
title="Build, then Deploy: picks up new commits from the repository. If the build fails, nothing is redeployed."
disabled={busy !== null}
onClick={() =>
withBusy("rebuild", async () => {
@@ -296,6 +352,10 @@ export function InstallationDetail({ onLoggedOut }: { onLoggedOut: () => void })
{busy === "delete" ? "Deleting…" : "Delete"}
</button>
</div>
<p className="card-hint" style={{ marginTop: 8 }}>
Build makes a new image from the repository. Deploy runs that image in a fresh container (Redeploy does the same
again). Rebuild &amp; redeploy does both, to pick up new commits.
</p>
</div>
<div className="card section-gap">
+21
View File
@@ -24,6 +24,27 @@
(`apps/server/src/proxy/mcpProxy.ts`, constant-time comparison) and proxied to the
container's IP on the shared network.
## Start / Stop / Restart vs Deploy
Two families of actions, both in `apps/server/src/service/orchestrator.ts`:
- **Build / Deploy** change what runs. Build re-clones the repo and produces a new image
(the running container is untouched). Deploy removes any existing container and creates a
new one from the built image, so it is the only way to apply changed env/config.
"Redeploy (env only)" is Deploy again with the current image; "Rebuild & redeploy" is Build
then Deploy (and stops before deploying if the build fails).
- **Start / Stop / Restart** only change whether the *existing* container runs
(`docker stop|start|restart`; nothing is removed or recreated, so they are fast and never
apply new env/config). Stop sets status `stopped`; the container's `unless-stopped` restart
policy keeps it stopped until started. Start and Restart set `starting`, wait for the
container to listen (same health check as Deploy), then `running` (or `error` with the
reason). If the container no longer exists they fall back to Deploy when the installation
has a built image, and report an error otherwise.
The proxy only serves installations in status `running`, so a stopped or restarting
installation answers 404 until it is healthy again. The per-container IP cache is dropped on
every start/stop/restart because the IP can change.
## Why the manager itself must run as a container
Rootless Podman isolates the host network namespace from the container bridge, so the