SkillAgentSearch skills...

Containers

Enhance your Workers with serverless containers

Install / Use

/learn @cloudflare/Containers
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

Containers

A class for interacting with Containers on Cloudflare Workers.

Features

  • HTTP request proxying and WebSocket forwarding
  • Simple container lifecycle management (starting and stopping containers)
  • Event hooks for container lifecycle events (onStart, onStop, onError)
  • Configurable sleep timeout that renews on requests
  • Load balancing utilities

Installation

npm install @cloudflare/containers

Basic Example

import { Container, getContainer, getRandom } from '@cloudflare/containers';

export class MyContainer extends Container {
  // Configure default port for the container
  defaultPort = 8080;
  // After 1 minute of no new activity, shutdown the container
  sleepAfter = '1m';
}

export default {
  async fetch(request, env) {
    const pathname = new URL(request.url).pathname;

    // If you want to route requests to a specific container,
    // pass a unique container identifier to .get()

    if (pathname.startsWith('/specific/')) {
      // In this case, each unique pathname will spawn a new container
      const container = env.MY_CONTAINER.getByName(pathname);
      return await container.fetch(request);
    }

    // Note: this is a temporary method until built-in autoscaling and load balancing are added.
    // If you want to route to one of many containers (in this case 5), use the getRandom helper.
    // This load balances incoming requests across these container instances.
    let container = await getRandom(env.MY_CONTAINER, 5);
    return await container.fetch(request);
  },
};

API Reference

Container Class

The Container class that extends a container-enbled Durable Object to provide additional container-specific functionality.

Properties

  • defaultPort?

    Optional default port to use when communicating with the container. If this is not set, or you want to target a specific port on your container, you can specify the port with fetch(switchPort(req, 8080)) or containerFetch(req, 8080).

  • requiredPorts?

    Array of ports that should be checked for availability during container startup. Used by startAndWaitForPorts when no specific ports are provided.

  • sleepAfter

    How long to keep the container alive without activity (format: number for seconds, or string like "5m", "30s", "1h").

    Defaults to "10m", meaning that after the Container class Durable Object receives no requests for 10 minutes, it will shut down the container.

The following properties are used to set defaults when starting the container, but can be overriden on a per-instance basis by passing in values to startAndWaitForPorts() or start().

  • env?: Record<string, string>

    Environment variables to pass to the container when starting up.

  • entrypoint?: string[]

    Specify an entrypoint to override image default.

  • enableInternet: boolean

    Whether to enable internet access for the container.

    Defaults to true.

  • pingEndpoint: string

    Specify an endpoint the container class will hit to check if the underlying instance started. This does not need to be set by the majority of people, only use it if you would like the container supervisor to hit another endpoint in your container when it starts it. Observe that pingEndpoint can include both the hostname and the path. You can set container/health, meaning "container" will be the value passed along the Host header, and "/health" the path.

    Defaults to ping.

Methods

Lifecycle Hooks

These lifecycle methods are automatically called when the container state transitions. Override these methods to use these hooks.

See this example.

  • onStart()

    Called when container starts successfully.

    • called when states transition from stopped -> running, running -> healthy
  • onStop()

    Called when container shuts down.

  • onError(error)

    Called when container encounters an error, and by default logs and throws the error.

  • onActivityExpired()

    Called when the activity is expired. The container will run continue to run for some time after the last activity - this length of time is configured by sleepAfter. By default, this stops the container with a SIGTERM, but you can override this behaviour, as with other lifecycle hooks. However, if you don't stop the container here, the activity tracker will be renewed, and this lifecycle hook will be called again when the timer re-expires.

Container Methods
  • fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>

    Forwards HTTP requests to the container.

    If you want to target a specific port on the container, rather than the default port, you should use switchPort like so:

    const container = env.MY_CONTAINER.getByName('id');
    await container.fetch(switchPort(request, 8080));
    

    Make sure you provide a port with switchPort or specify a port with the defaultPort property.

    You must use fetch rather than containerFetch if you want to forward websockets.

    Note that when you call any of the fetch functions, the activity will be automatically renewed (sleepAfter time starts after last activity), and the container will be started if not already running.

  • containerFetch(...)

    Note: containerFetch does not work with websockets.

    Sends an HTTP request to the container. Supports both standard fetch API signatures:

    • containerFetch(request, port?): Traditional signature with Request object
    • containerFetch(url, init?, port?): Standard fetch-like signature with URL string/object and RequestInit options
  • startAndWaitForPorts(args: StartAndWaitForPortsOptions): Promise<void>

    Starts the container and then waits for specified ports to be ready. Prioritises ports passed in to the function, then requiredPorts if set, then defaultPort.

    interface StartAndWaitForPortsOptions {
      startOptions?: {
        /** Environment variables to pass to the container */
        envVars?: Record<string, string>;
        /** Custom entrypoint to override container default */
        entrypoint?: string[];
        /** Whether to enable internet access for the container */
        enableInternet?: boolean;
      };
      /** Ports to check */
      ports?: number | number[];
      cancellationOptions?: {
        /** Abort signal to cancel start and port checking */
        abort?: AbortSignal;
        /** Max time to wait for container to start, in milliseconds */
        instanceGetTimeoutMS?: number;
        /** Max time to wait for ports to be ready, in milliseconds */
        portReadyTimeoutMS?: number;
        /** Polling interval for checking container has started or ports are ready, in milliseconds */
        waitInterval?: number;
      };
    }
    
  • start(startOptions?: ContainerStartConfigOptions, waitOptions?: WaitOptions)

    Starts the container, without waiting for any ports to be ready.

    You might want to use this instead of startAndWaitForPorts if you want to:

    • Start a container without blocking until a port is available
    • Initialize a container that doesn't expose ports
    • Perform custom port availability checks separately

    Options:

    interface ContainerStartConfigOptions {
      /** Environment variables to pass to the container */
      envVars?: Record<string, string>;
      /** Custom entrypoint to override container default */
      entrypoint?: string[];
      /** Whether to enable internet access for the container */
      enableInternet?: boolean;
    }
    
    interface WaitOptions {
      /** The port number to check for readiness */
      portToCheck: number;
      /** Optional AbortSignal, use this to abort waiting for ports */
      signal?: AbortSignal;
      /** Number of attempts to wait for port to be ready */
      retries?: number;
      /** Time to wait in between polling port for readiness, in milliseconds */
      waitInterval?: number;
    }
    
  • stop(signal = SIGTERM): Promise<void>

    Sends the specified signal to the container. Triggers onStop.

  • destroy(): Promise<void>

    Forcefully destroys the container (sends SIGKILL). Triggers onStop.

  • getState(): Promise<State>

    Get the current container state.

    type State = {
      lastChange: number;
    } & (
      | {
          // 'running' means that the container is trying to start and is transitioning to a healthy status.
          //           onStop might be triggered if there is an exit code, and it will transition to 'stopped'.
          status: 'running' | 'stopping' | 'stopped' | 'healthy';
        }
      | {
          status: 'stopped_with_code';
          exitCode?: number;
        }
    );
    
  • renewActivityTimeout()

    Manually renews the container activity timeout (extends container lifetime).

  • schedule<T = string>(when: Date | number, callback: string, payload?: T): Promise<Schedule<T>>

    Options:

    • when: When to execute the task (Date object or number of seconds delay)
    • callback: Name of the function to call as a string
    • payload: Data to pass to the callback

    Instead of using the default alarm handler, use schedule() instead. The default alarm handler is in charge of renewing the container activity and keeping the durable object alive. You can override alarm(), but because its functionality is currently vital to managing the container lifecycle, we recommend calling schedule to schedule tasks instead.

Utility Functions

  • getRandom(binding, instances?: number)

    Get a random container instances across N instances. This is useful for load balancing. Returns a stub for the container. See example.

  • getContainer(binding, name?: string) Helper to get a particular container instance stub.

    e.g. const container = getContainer(env.CONTAINER, "unique-id")

    If no name is provided, "cf-singleton-container" is used.

Examples

HTTP Example with Lifecycle Hooks

import { Container } from '@cloudfla
View on GitHub
GitHub Stars234
CategoryDevelopment
Updated1h ago
Forks27

Languages

TypeScript

Security Score

85/100

Audited on Mar 21, 2026

No findings