### Durable Object Container Initialization Example Source: https://developers.cloudflare.com/containers/llms-full.txt Example of how to initialize and start a container when a Durable Object boots. ```APIDOC ## Initialization Example ### JavaScript ```javascript export class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); // boot the container when starting the DO this.ctx.blockConcurrencyWhile(async () => { this.ctx.container.start(); }); } } ``` ### TypeScript ```typescript export class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); // boot the container when starting the DO this.ctx.blockConcurrencyWhile(async () => { this.ctx.container.start(); }); } } ``` ``` -------------------------------- ### Start Container and Wait for Ports (TypeScript) Source: https://developers.cloudflare.com/containers/container-class This TypeScript example demonstrates starting a container and waiting for specific ports, with custom environment variables and an extended port readiness timeout. ```typescript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.API_CONTAINER, "tenant-42"); await container.startAndWaitForPorts({ ports: [8080, 9222], startOptions: { envVars: { API_KEY: env.API_KEY, TENANT_ID: "tenant-42", }, }, cancellationOptions: { portReadyTimeoutMS: 30_000, }, }); }, }; ``` -------------------------------- ### Start and Wait for Ports in TypeScript Source: https://developers.cloudflare.com/containers/llms-full.txt TypeScript example demonstrating how to start a container and wait for specific ports, configuring environment variables and a custom port ready timeout. This ensures the container is fully initialized before proceeding. ```typescript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.API_CONTAINER, "tenant-42"); await container.startAndWaitForPorts({ ports: [8080, 9222], startOptions: { envVars: { API_KEY: env.API_KEY, TENANT_ID: "tenant-42", }, }, cancellationOptions: { portReadyTimeoutMS: 30_000, }, }); }, }; ``` -------------------------------- ### Start Container with Entrypoint and Env Vars (JavaScript) Source: https://developers.cloudflare.com/containers/container-class Use this to start a container for batch jobs or cron tasks, or when managing readiness manually. It allows overriding the entrypoint and setting environment variables. Internet access is disabled in this example. ```javascript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.JOB_CONTAINER, "nightly-report"); await container.start({ entrypoint: ["node", "scripts/nightly-report.js"], envVars: { REPORT_DATE: new Date().toISOString(), }, enableInternet: false, }); }, }; ``` -------------------------------- ### JavaScript: Implement onStart for Container Fetch Source: https://developers.cloudflare.com/containers/llms-full.txt Example of implementing the onStart method in JavaScript to perform an HTTP POST request to a local bootstrap endpoint after the container starts. Ensure the container is configured with a default port. ```javascript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { defaultPort = 8080; async onStart() { await this.containerFetch("http://localhost/bootstrap", { method: "POST", }); } } ``` -------------------------------- ### TypeScript: Implement onStart for Container Fetch Source: https://developers.cloudflare.com/containers/llms-full.txt Example of implementing the onStart method in TypeScript to perform an HTTP POST request to a local bootstrap endpoint after the container starts. Ensure the container is configured with a default port. ```typescript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { defaultPort = 8080; override async onStart() { await this.containerFetch("http://localhost/bootstrap", { method: "POST", }); } } ``` -------------------------------- ### Start and Wait for Ports in JavaScript Source: https://developers.cloudflare.com/containers/llms-full.txt Example of starting a container and waiting for ports 8080 and 9222 to be ready using environment variables for API key and tenant ID. The port ready timeout is extended to 30,000ms. ```javascript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.API_CONTAINER, "tenant-42"); await container.startAndWaitForPorts({ ports: [8080, 9222], startOptions: { envVars: { API_KEY: env.API_KEY, TENANT_ID: "tenant-42", }, }, cancellationOptions: { portReadyTimeoutMS: 30_000, }, }); }, }; ``` -------------------------------- ### Install @cloudflare/containers with bun Source: https://developers.cloudflare.com/containers/llms-full.txt Install the @cloudflare/containers package using bun. ```bash bun add @cloudflare/containers ``` -------------------------------- ### JavaScript Example Source: https://developers.cloudflare.com/containers/container-class Example of how to use the startAndWaitForPorts method in JavaScript. ```javascript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.API_CONTAINER, "tenant-42"); await container.startAndWaitForPorts({ ports: [8080, 9222], startOptions: { envVars: { API_KEY: env.API_KEY, TENANT_ID: "tenant-42", }, }, cancellationOptions: { portReadyTimeoutMS: 30000, }, }); }, }; ``` -------------------------------- ### Get and Start Container Instances Source: https://developers.cloudflare.com/containers/platform-details/scaling-and-routing This TypeScript code demonstrates how to retrieve and start two container instances using their environment variables and unique IDs. It assumes the existence of a `getContainer` function and `startAndWaitForPorts` method. ```typescript // get and start two container instances const containerOne = getContainer( env.MY_CONTAINER, idOne, ).startAndWaitForPorts(); const containerTwo = getContainer( env.MY_CONTAINER, idTwo, ).startAndWaitForPorts(); ``` -------------------------------- ### Start Container with Environment Variables and Entrypoint Override (TypeScript) Source: https://developers.cloudflare.com/containers/llms-full.txt Starts a container with specific environment variables and an entrypoint override using TypeScript. This example is suitable for cron tasks where internet access is disabled. ```TypeScript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.JOB_CONTAINER, "nightly-report"); await container.start({ entrypoint: ["node", "scripts/nightly-report.js"], envVars: { REPORT_DATE: new Date().toISOString(), }, enableInternet: false, }); }, }; ``` -------------------------------- ### Start a Container Source: https://developers.cloudflare.com/durable-objects/api/container Boots a container. This method does not block until the container is fully started. You may want to confirm the container is ready to accept requests before using it. ```javascript this.ctx.container.start({ env: { FOO: "bar", }, enableInternet: false, entrypoint: ["node", "server.js"], }); ``` -------------------------------- ### JavaScript Example: Setting and Handling Alarms Source: https://developers.cloudflare.com/durable-objects/api/alarms Example demonstrating how to set an alarm using `setAlarm()` and handle it with the `alarm()` method in JavaScript. ```APIDOC ## JavaScript Example: Setting and Handling Alarms ### Description This example shows how to both set alarms with the `setAlarm(timestamp)` method and handle alarms with the `alarm()` handler within your Durable Object. - The `alarm()` handler will be called once every time an alarm fires. - If an unexpected error terminates the Durable Object, the `alarm()` handler may be re-instantiated on another machine. - Following a short delay, the `alarm()` handler will run from the beginning on the other machine. ### Method `fetch` and `alarm` ### Endpoint `/` (for fetch requests) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None for `alarm` handler. `fetch` handles standard HTTP requests. ### Request Example ```javascript // Example fetch request to trigger initial alarm setting // POST / or GET / ``` ### Response #### Success Response (200 for fetch) Returns a response to the fetch request. The `alarm` handler itself returns void. #### Response Example ```json // Example response for fetch request { "message": "Alarm set or checked" } ``` ### Code Example (JavaScript) ```javascript import { DurableObject } from "cloudflare:workers"; export default { async fetch(request, env) { return await env.ALARM_EXAMPLE.getByName("foo").fetch(request); }, }; const SECONDS = 1000; export class AlarmExample extends DurableObject { constructor(ctx, env) { super(ctx, env); this.storage = ctx.storage; } async fetch(request) { // If there is no alarm currently set, set one for 10 seconds from now let currentAlarm = await this.storage.getAlarm(); if (currentAlarm == null) { this.storage.setAlarm(Date.now() + 10 * SECONDS); } return new Response("Alarm checked/set"); } async alarm() { // The alarm handler will be invoked whenever an alarm fires. // You can use this to do work, read from the Storage API, make HTTP calls // and set future alarms to run using this.storage.setAlarm() from within this handler. console.log("Alarm fired!"); // Example: Set the next alarm for 10 seconds later this.storage.setAlarm(Date.now() + 10 * SECONDS); } } ``` ``` -------------------------------- ### Python Example: Setting and Handling Alarms Source: https://developers.cloudflare.com/durable-objects/api/alarms Example demonstrating how to set an alarm using `setAlarm()` and handle it with the `alarm()` method in Python. ```APIDOC ## Python Example: Setting and Handling Alarms ### Description This example shows how to both set alarms with the `setAlarm(timestamp)` method and handle alarms with the `alarm()` handler within your Durable Object using Python. - The `alarm()` handler will be called once every time an alarm fires. - If an unexpected error terminates the Durable Object, the `alarm()` handler may be re-instantiated on another machine. - Following a short delay, the `alarm()` handler will run from the beginning on the other machine. ### Method `fetch` and `alarm` ### Endpoint `/` (for fetch requests) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None for `alarm` handler. `fetch` handles standard HTTP requests. ### Request Example ```python # Example fetch request to trigger initial alarm setting # POST / or GET / ``` ### Response #### Success Response (200 for fetch) Returns a response to the fetch request. The `alarm` handler itself returns void. #### Response Example ```json { "message": "Alarm set or checked" } ``` ### Code Example (Python) ```python import time from workers import DurableObject, WorkerEntrypoint class Default(WorkerEntrypoint): async def fetch(self, request): return await self.env.ALARM_EXAMPLE.getByName("foo").fetch(request) SECONDS = 1000 class AlarmExample(DurableObject): def __init__(self, ctx, env): super().__init__(ctx, env) self.storage = ctx.storage async def fetch(self, request): # If there is no alarm currently set, set one for 10 seconds from now current_alarm = await self.storage.getAlarm() if current_alarm is None: self.storage.setAlarm(int(time.time() * 1000) + 10 * SECONDS) return Response("Alarm checked/set") async def alarm(self): # The alarm handler will be invoked whenever an alarm fires. # You can use this to do work, read from the Storage API, make HTTP calls # and set future alarms to run using self.storage.setAlarm() from within this handler. print("Alarm fired!") # Example: Set the next alarm for 10 seconds later self.storage.setAlarm(int(time.time() * 1000) + 10 * SECONDS) ``` ``` -------------------------------- ### Install @cloudflare/containers with yarn Source: https://developers.cloudflare.com/containers/llms-full.txt Install the @cloudflare/containers package using yarn. ```bash yarn add @cloudflare/containers ``` -------------------------------- ### Start Container and Wait for Ports (JavaScript) Source: https://developers.cloudflare.com/containers/container-class Use this method to start a container and ensure it's ready before sending traffic. It allows configuration of environment variables and port readiness timeouts. ```javascript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.API_CONTAINER, "tenant-42"); await container.startAndWaitForPorts({ ports: [8080, 9222], startOptions: { envVars: { API_KEY: env.API_KEY, TENANT_ID: "tenant-42", }, }, cancellationOptions: { portReadyTimeoutMS: 30_000, }, }); }, }; ``` -------------------------------- ### Start a Container Instance Source: https://developers.cloudflare.com/containers/llms-full.txt Initiates the start of a container instance. Cloudflare selects the nearest free instance from pre-initialized locations. ```javascript this.ctx.container.start ``` -------------------------------- ### Install @cloudflare/containers with pnpm Source: https://developers.cloudflare.com/containers/llms-full.txt Install the @cloudflare/containers package using pnpm. ```bash pnpm add @cloudflare/containers ``` -------------------------------- ### Basic Fetch Handler Example Source: https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch This is a basic example of a fetch handler that returns a simple 'Hello World!' response. Ensure your Worker is configured to export this handler. ```javascript export default { async fetch(request, env, ctx) { return new Response('Hello World!'); }, }; ``` -------------------------------- ### Install @cloudflare/containers with npm Source: https://developers.cloudflare.com/containers/llms-full.txt Install the @cloudflare/containers package using npm. ```bash npm i @cloudflare/containers ``` -------------------------------- ### Basic Durable Object Example Source: https://developers.cloudflare.com/durable-objects/api/base A simple example of a Durable Object with a fetch handler that responds to a '/hello' path. ```APIDOC ## POST /api/users ### Description This endpoint allows for the creation of new users within the system. It requires user details in the request body. ### Method POST ### Endpoint /api/users ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **username** (string) - Required - The desired username for the new user. * **email** (string) - Required - The email address of the new user. * **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "johndoe", "email": "john.doe@example.com", "password": "securepassword123" } ``` ### Response #### Success Response (201 Created) * **userId** (string) - The unique identifier for the newly created user. * **message** (string) - A confirmation message. #### Response Example ```json { "userId": "usr_12345abcde", "message": "User created successfully." } ``` ``` -------------------------------- ### Start Container with Environment Variables and Entrypoint Override Source: https://developers.cloudflare.com/containers/llms-full.txt Starts a container with specific environment variables and an entrypoint override. Useful for batch jobs or cron tasks where internet access is not required. ```JavaScript import { getContainer } from "@cloudflare/containers"; export default { async scheduled(_event, env) { const container = getContainer(env.JOB_CONTAINER, "nightly-report"); await container.start({ entrypoint: ["node", "scripts/nightly-report.js"], envVars: { REPORT_DATE: new Date().toISOString(), }, enableInternet: false, }); }, }; ``` -------------------------------- ### Basic Fetch Handler Example Source: https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch A minimal example of a Cloudflare Worker using the Fetch API to handle requests. This worker responds with a simple 'Hello, World!' message. ```javascript export default { async fetch(request) { return new Response("Hello World!"); } }; ``` -------------------------------- ### Workers KV SDK - TypeScript Examples Source: https://developers.cloudflare.com/kv Examples demonstrating how to use the Cloudflare SDK for TypeScript to interact with Workers KV. ```APIDOC ## Cloudflare SDK for TypeScript ### Initialize Client ```typescript import { Cloudflare } from '@cloudflare/workers-types'; const client = new Cloudflare({ apiEmail: process.env['CLOUDFLARE_EMAIL'], apiKey: process.env['CLOUDFLARE_API_KEY'], }); ``` ### Update Key-Value Pair ```typescript // Assuming client is initialized as above const kvNamespaceId = ''; const key = 'KEY'; const valueToSet = 'VALUE'; const accountId = ''; const updatedValue = await client.kv.namespaces.values.update(kvNamespaceId, key, { account_id: accountId, value: valueToSet, }); console.log('Value updated:', updatedValue); ``` ### Get Key-Value Pair ```typescript // Assuming client is initialized as above const kvNamespaceId = ''; const key = 'KEY'; const accountId = ''; const retrievedValue = await client.kv.namespaces.values.get(kvNamespaceId, key, { account_id: accountId, }); console.log('Retrieved value:', retrievedValue); ``` ### Delete Key-Value Pair ```typescript // Assuming client is initialized as above const kvNamespaceId = ''; const key = 'KEY'; const accountId = ''; await client.kv.namespaces.values.delete(kvNamespaceId, key, { account_id: accountId, }); console.log('Key deleted successfully.'); ``` ### List KV Namespaces ```typescript // Assuming client is initialized as above const accountId = ''; for await (const namespace of client.kv.namespaces.list({ account_id: accountId })) { console.log('Namespace ID:', namespace.id); console.log('Namespace Label:', namespace.label); } ``` ``` -------------------------------- ### Local Development Secrets Example Source: https://developers.cloudflare.com/workers/configuration/secrets This example shows how to define sensitive keys and API tokens for local development using either a .dev.vars or .env file. These files should not be committed to version control. ```dotenv SECRET_KEY="value" API_TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" ``` -------------------------------- ### Create and Run a Cloudflare Agents Starter Project Source: https://developers.cloudflare.com/agents Use these commands to quickly set up a new agent project with Cloudflare's starter template. This includes streaming AI chat, server-side and client-side tools, and task scheduling. No API keys are required as it defaults to Workers AI. ```bash npx create-cloudflare@latest --template cloudflare/agents-starter cd agents-starter && npm install npm run dev ``` -------------------------------- ### Get Container Stub by Name (TypeScript) Source: https://developers.cloudflare.com/containers/llms-full.txt This TypeScript example shows how to use `getContainer` to get a stub for a specific container instance by its stable name. This is ideal for per-user or per-document container instances. ```typescript import { getContainer } from "@cloudflare/containers"; export default { async fetch(request: Request, env) { const { sessionId } = await request.json(); return getContainer(env.MY_CONTAINER, sessionId).fetch(request); }, }; ``` -------------------------------- ### Get and start two container instances Source: https://developers.cloudflare.com/containers/llms-full.txt Retrieve and start specific container instances using their unique IDs. Each instance will run until its `sleepAfter` time elapses or it is manually stopped, providing explicit control over their lifecycle. ```typescript const containerOne = getContainer( env.MY_CONTAINER, idOne, ).startAndWaitForPorts(); const containerTwo = getContainer( env.MY_CONTAINER, idTwo, ).startAndWaitForPorts(); ``` -------------------------------- ### Workers KV REST API - GET Key-Value Pair Source: https://developers.cloudflare.com/kv Example of how to retrieve a key-value pair from Workers KV using cURL. ```APIDOC ## GET /accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME ### Description Retrieves the value associated with a given key from a Workers KV namespace. ### Method GET ### Endpoint `/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME` ### Parameters #### Path Parameters - **$ACCOUNT_ID** (string) - Required - Your Cloudflare account ID. - **$NAMESPACE_ID** (string) - Required - The ID of the KV namespace. - **$KEY_NAME** (string) - Required - The name of the key to retrieve. #### Headers - **X-Auth-Email** (string) - Required - Your Cloudflare account email. - **X-Auth-Key** (string) - Required - Your Cloudflare API key. ### Response #### Success Response (200) - **value** (string) - The value associated with the key. ### Request Example ```curl curl https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/storage/kv/namespaces/$NAMESPACE_ID/values/$KEY_NAME \ -H "X-Auth-Email: $CLOUDFLARE_EMAIL" \ -H "X-Auth-Key: $CLOUDFLARE_API_KEY" ``` ``` -------------------------------- ### Get a Container Instance by ID Source: https://developers.cloudflare.com/containers/llms-full.txt Retrieves a container instance using its ID. If the instance is new or has slept, this may result in a cold start. ```javascript env.MY_CONTAINER.get(id) ``` -------------------------------- ### Intercept Outbound HTTP/HTTPS Traffic in JavaScript Source: https://developers.cloudflare.com/sandbox/guides/outbound-traffic Define an `outbound` handler to intercept all HTTP and HTTPS requests. This example logs GET requests and blocks others. ```javascript import { Sandbox, ContainerProxy } from "@cloudflare/sandbox";export { ContainerProxy }; export class MySandbox extends Sandbox {} MySandbox.outbound = async (request, env, ctx) => { if (request.method !== "GET") { console.log(`Blocked ${request.method} to ${request.url}`); return new Response("Method Not Allowed", { status: 405 }); } return fetch(request);}; ``` -------------------------------- ### Worker Triggering a Cron Container Source: https://developers.cloudflare.com/containers/examples/cron TypeScript code for a Cloudflare Worker that defines a CronContainer and starts it from the scheduled handler. This example includes basic container lifecycle logging. ```typescript import { Container, getContainer } from '@cloudflare/containers'; export class CronContainer extends Container { sleepAfter = '10s'; override onStart() { console.log('Starting container'); } override onStop() { console.log('Container stopped'); } } export default { async fetch(): Promise { return new Response("This Worker runs a cron job to execute a container on a schedule."); }, async scheduled(_controller: any, env: { CRON_CONTAINER: DurableObjectNamespace }) { let container = getContainer(env.CRON_CONTAINER); await container.start({ envVars: { MESSAGE: "Start Time: " + new Date().toISOString(), } }) }, }; ``` -------------------------------- ### Create Bucket Mounting Startup Script Source: https://developers.cloudflare.com/containers/examples/r2-fuse-mount A shell script to create a mount point, start tigrisfs in the background to mount an R2 bucket, and list its contents. This script is executed at container startup. ```shell # Create startup script that mounts bucket and runs a commandRUN printf '#!/bin/sh\n\ set -e\n\ \n\ mkdir -p /mnt/r2\n\ \n\ R2_ENDPOINT="https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com"\n\ echo "Mounting bucket ${R2_BUCKET_NAME}..."\n\ /usr/local/bin/tigrisfs --endpoint "${R2_ENDPOINT}" -f "${R2_BUCKET_NAME}" /mnt/r2 &\n\ sleep 3\n\ \n\ echo "Contents of mounted bucket:"\n\ ls -lah /mnt/r2\n\ ' > /startup.sh && chmod +x /startup.sh ``` -------------------------------- ### Container Status Hooks Example Source: https://developers.cloudflare.com/containers/examples/status-hooks This TypeScript code defines a custom container that overrides lifecycle methods to log container status changes. It demonstrates how to handle start, stop, idle, and error events. ```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); }} ``` -------------------------------- ### Build and Push Docker Image in One Step (npm) Source: https://developers.cloudflare.com/containers/llms-full.txt Build a Docker image and push it to the Cloudflare Registry simultaneously using npm. The `-p` flag enables pushing. Replace `` with your desired tag. ```bash npx wrangler containers build -p -t . ``` -------------------------------- ### Get Random Container Stub (TypeScript) Source: https://developers.cloudflare.com/containers/llms-full.txt This TypeScript example uses `getRandom` to fetch a stub for a randomly chosen container instance from a pool. It's designed for distributing requests across multiple stateless container instances. ```typescript import { getRandom } from "@cloudflare/containers"; export default { async fetch(request: Request, env) { const container = await getRandom(env.WORKER_POOL, 5); return container.fetch(request); }, }; ``` -------------------------------- ### Lifecycle Hook: onStart Source: https://developers.cloudflare.com/containers/container-class Implement custom logic to run after the container has successfully started. ```APIDOC ## Lifecycle Hook: `onStart` ### Description Run Worker code after the container has started. ### Method Signature ```typescript onStart(): void | Promise ``` ### Returns - **Type**: `void | Promise` - **Description**: Resolve after any startup logic finishes. ### Usage Use this to log startup, seed data, or schedule recurring tasks with `schedule()`. ### Example (TypeScript) ```typescript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { defaultPort = 8080; override async onStart(): Promise { await this.containerFetch("http://localhost/bootstrap", { method: "POST", }); } } ``` ### Example (JavaScript) ```javascript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { defaultPort = 8080; async onStart() { await this.containerFetch("http://localhost/bootstrap", { method: "POST", }); } } ``` ``` -------------------------------- ### Wait for Specific Port Readiness (JavaScript) Source: https://developers.cloudflare.com/containers/container-class This JavaScript example shows how to use `waitForPort` after starting a container to poll a specific port (9222) for readiness. It configures retries and the interval between checks. The returned retry count is logged. ```javascript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { async warmInspector() { await this.start(); const retryCount = await this.waitForPort({ portToCheck: 9222, retries: 20, waitInterval: 500, }); console.log("Inspector port became ready:", retryCount); } } ``` -------------------------------- ### Manage Logpush with Python Source: https://developers.cloudflare.com/logs/logpush Manage Logpush jobs using a Python script. This example demonstrates how to list existing Logpush jobs for a zone. You will need to install the 'requests' library and replace placeholders with your actual zone ID and API token. ```python import requests ZONE_ID = "" API_TOKEN = "" headers = { "Authorization": f"Bearer {API_TOKEN}", "Content-Type": "application/json" } response = requests.get(f"https://api.cloudflare.com/client/v4/zones/{ZONE_ID}/logpush/jobs", headers=headers) if response.status_code == 200: print("Logpush jobs:") for job in response.json()["result"]: print(f"- {job['name']} ({job['dataset']}) - Enabled: {job['enabled']}") else: print(f"Error: {response.status_code} - {response.text}") ``` -------------------------------- ### Access Secret in Worker Source: https://developers.cloudflare.com/secrets-store/integrations/workers Access secrets bound to your Worker via the `env` object. Use an asynchronous call to `get()` on the binding variable. Note that production secrets cannot be accessed from local development setups without specific Wrangler commands. ```javascript export default { async fetch(request, env) { // Example of using the secret safely in an API request const APIkey = await env..get() const response = await fetch("https://api.example.com/data", { headers: { "Authorization": `Bearer ${APIKey}` }, }); if (!response.ok) { return new Response("Failed to fetch data", { status: response.status }); } const data = await response.json(); return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" }, }); }, }; ``` -------------------------------- ### onStart Method Source: https://developers.cloudflare.com/containers/llms-full.txt Run Worker code after the container has started. Use this to log startup, seed data, or schedule recurring tasks. ```APIDOC ## onStart ### Description Run Worker code after the container has started. ### Method `onStart(): void | Promise` ### Returns `void | Promise` - Resolve after any startup logic finishes. ### Usage Use this to log startup, seed data, or schedule recurring tasks with [schedule()](#schedule). ### Request Example ```typescript import { Container } from "@cloudflare/containers"; export class MyContainer extends Container { defaultPort = 8080; async onStart() { await this.containerFetch("http://localhost/bootstrap", { method: "POST", }); } } ``` ``` -------------------------------- ### Build and Push Docker Image in One Step (pnpm) Source: https://developers.cloudflare.com/containers/llms-full.txt Build a Docker image and push it to the Cloudflare Registry simultaneously using pnpm. The `-p` flag enables pushing. Replace `` with your desired tag. ```bash pnpm wrangler containers build -p -t . ``` -------------------------------- ### Deploy Container with Immediate Rollout (npm) Source: https://developers.cloudflare.com/containers/platform-details/rollouts Use this command to deploy your container with an immediate rollout strategy. Ensure you have Wrangler CLI installed. ```bash npx wrangler deploy --containers-rollout=immediate ``` -------------------------------- ### Configure Explicit Placement Hint (wrangler.toml) Source: https://developers.cloudflare.com/workers/configuration/placement Configure an explicit cloud region for your Worker using the `placement.region` setting in your `wrangler.toml` file. This ensures your Worker runs in the data center with the lowest latency to your specified cloud region. ```toml [placement] region = "aws:us-east-1" ``` -------------------------------- ### Get Container Info Source: https://developers.cloudflare.com/workers/wrangler/commands/containers Get information about a specific Container, including top-level details and a list of instances. ```APIDOC ## GET /containers/info/{CONTAINER_ID} ### Description Get information about a specific Container, including top-level details and a list of instances. ### Method GET ### Endpoint `/containers/info/{CONTAINER_ID}` ### Parameters #### Path Parameters - **CONTAINER_ID** (string) - Required - The ID of the Container to get information about. ``` -------------------------------- ### Access Wrangler Documentation with npm Source: https://developers.cloudflare.com/workers/wrangler/commands/general Use this command to open the Cloudflare developer documentation in your default browser using npm. Replace '[SEARCH]' with your query. ```bash npx wrangler docs [SEARCH] ``` -------------------------------- ### Initialize API Client with Global `env` (Python) Source: https://developers.cloudflare.com/workers/runtime-apis/bindings This Python example demonstrates initializing an API client using globally accessible environment variables or secrets. It sets a default log level if not explicitly provided. ```python from workers import WorkerEntrypoint, env from example_api_client import ApiClient api_client = ApiClient(api_key=env.API_KEY) LOG_LEVEL = getattr(env, "LOG_LEVEL", "info") class Default(WorkerEntrypoint): async def fetch(self, request): # ... pass ``` -------------------------------- ### Durable Object Implementation Examples Source: https://developers.cloudflare.com/durable-objects/api/base Examples of implementing a Durable Object in JavaScript, TypeScript, and Python, including the fetch handler. ```APIDOC ## Durable Object Implementation Examples ### Description Provides examples of how to define a Durable Object class that extends the `DurableObject` base class and implements the `fetch` handler. ### JavaScript Example ```javascript export class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); } async fetch(request) { return new Response("Hello, World!"); } } ``` ### TypeScript Example ```typescript export class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); } async fetch(request: Request): Promise { return new Response("Hello, World!"); } } ``` ### Python Example ```python from workers import DurableObject, Response class MyDurableObject(DurableObject): def __init__(self, ctx, env): super().__init__(ctx, env) async def fetch(self, request): return Response("Hello, World!") ``` ``` -------------------------------- ### Configure Container with Basic Settings (TOML) Source: https://developers.cloudflare.com/workers/wrangler/configuration TOML equivalent for configuring a container with class name, Dockerfile, max instances, instance type, image variables, and constraints. This format is an alternative to JSONC for configuration. ```toml [[containers]] class_name = "MyContainer" image = "./Dockerfile" max_instances = 10 instance_type = "basic" [containers.image_vars] FOO = "BAR" [containers.constraints] regions = [ "ENAM", "WNAM" ] jurisdiction = "fedramp" [[durable_objects.bindings]] name = "MY_CONTAINER" class_name = "MyContainer" [[migrations]] tag = "v1" new_sqlite_classes = [ "MyContainer" ] ``` -------------------------------- ### Create a new Worker with a Container template Source: https://developers.cloudflare.com/containers/get-started Use this command to create and deploy a new Worker with a container from the starter template. Ensure Docker is running locally. ```bash npm create cloudflare@latest -- --template=cloudflare/templates/containers-template ``` ```bash yarn create cloudflare --template=cloudflare/templates/containers-template ``` ```bash pnpm create cloudflare@latest --template=cloudflare/templates/containers-template ```