Skip to content

Status Hooks

Last reviewed: 10 months ago

Execute Workers code in reaction to Container status changes

When a Container starts, stops, becomes idle, and errors, it can trigger code execution in a Worker that has defined status hooks on the Container class. Refer to the Container package docs for more details.

TypeScript
import { Container } from "@cloudflare/containers";
export class MyContainer extends Container {
defaultPort = 4000;
sleepAfter = "5m";
override onStart() {
console.log("Container successfully started");
}
override onStop(stopParams) {
if (stopParams.exitCode === 0) {
console.log("Container stopped gracefully");
} else {
console.log("Container stopped with exit code:", stopParams.exitCode);
}
console.log("Container stop reason:", stopParams.reason);
}
override async onActivityExpired() {
console.log("Container became idle, stopping it now");
await this.stop();
}
override onError(error: string) {
console.log("Container error:", error);
}
}