Use exec() to start another process inside a running container. The examples call exec() on this.ctx.container inside a class that extends DurableObject.
exec() does not start a stopped container. It waits for a container that is still starting. The examples on this page call a startContainer() method that starts the container when it is not running:
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
startContainer() {
const container = this.ctx.container;
if (!container.running) {
// With the `default` scheduling policy, call `container.start()` without options.
container.start({
image: container.images.base,
enableInternet: false,
});
}
return container;
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
startContainer() {
const container = this.ctx.container!;
if (!container.running) {
// With the `default` scheduling policy, call `container.start()` without options.
container.start({
image: container.images.base,
enableInternet: false,
});
}
return container;
}
}The following method runs a preparation command each time it starts the container. You can execute any series of startup commands after start(). output() buffers standard output and standard error as separate ArrayBuffer values.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async startAndPrepare() {
const container = this.ctx.container;
if (container.running) {
return;
}
container.start({
image: container.images.base,
enableInternet: false,
});
const process = await container.exec(["node", "scripts/prepare.js"]);
const output = await process.output();
const decoder = new TextDecoder();
if (output.exitCode !== 0) {
throw new Error(
`Container preparation failed: ${decoder.decode(output.stderr)}`,
);
}
console.log(decoder.decode(output.stdout));
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async startAndPrepare() {
const container = this.ctx.container!;
if (container.running) {
return;
}
container.start({
image: container.images.base,
enableInternet: false,
});
const process = await container.exec(["node", "scripts/prepare.js"]);
const output = await process.output();
const decoder = new TextDecoder();
if (output.exitCode !== 0) {
throw new Error(
`Container preparation failed: ${decoder.decode(output.stderr)}`,
);
}
console.log(decoder.decode(output.stdout));
}
}In a remote procedure call (RPC) method, ensure the container is running before calling exec(). Standard output uses a readable stream by default.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async readVersion() {
const container = this.startContainer();
const process = await container.exec(["node", "--version"]);
const stdout = process.stdout
? await new Response(process.stdout).text()
: "";
const exitCode = await process.exitCode;
return { pid: process.pid, stdout, exitCode };
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async readVersion() {
const container = this.startContainer();
const process = await container.exec(["node", "--version"]);
const stdout = process.stdout
? await new Response(process.stdout).text()
: "";
const exitCode = await process.exitCode;
return { pid: process.pid, stdout, exitCode };
}
}The returned pid identifies the new process. The exitCode promise resolves when that process exits.
The exec() operation starts the executable directly with the provided argument array. It does not start a shell first.
Each array item becomes one argument. Shell features such as pipes, redirects, globbing, and variable expansion do not run implicitly.
Invoke a shell when your command needs those features. Use ["bash", "-lc", "<COMMAND>"] if Bash exists in your image. Use ["sh", "-c", "<COMMAND>"] if the image only provides a Portable Operating System Interface (POSIX) shell. Pass untrusted values as separate arguments instead of interpolating them into a shell command string.
Pass a ReadableStream to send existing data. Setting stdout to "ignore" discards standard output.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async importData(data) {
const container = this.startContainer();
const stdin = new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode(data));
controller.close();
},
});
const process = await container.exec(["cat"], {
stdin,
stdout: "ignore",
});
const output = await process.output();
return {
stdoutBytes: output.stdout.byteLength,
exitCode: output.exitCode,
};
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async importData(data: string) {
const container = this.startContainer();
const stdin = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode(data));
controller.close();
},
});
const process = await container.exec(["cat"], {
stdin,
stdout: "ignore",
});
const output = await process.output();
return {
stdoutBytes: output.stdout.byteLength,
exitCode: output.exitCode,
};
}
}Ignored standard output produces an empty buffer from output(). Set stdin to "pipe" to write data over time.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async concatenateInput() {
const container = this.startContainer();
const process = await container.exec(["cat"], {
stdin: "pipe",
});
const writer = process.stdin?.getWriter();
if (!writer) {
throw new Error("Standard input is unavailable");
}
const encoder = new TextEncoder();
await writer.write(encoder.encode("first\n"));
await writer.write(encoder.encode("second\n"));
await writer.close();
const output = await process.output();
return new TextDecoder().decode(output.stdout);
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async concatenateInput() {
const container = this.startContainer();
const process = await container.exec(["cat"], {
stdin: "pipe",
});
const writer = process.stdin?.getWriter();
if (!writer) {
throw new Error("Standard input is unavailable");
}
const encoder = new TextEncoder();
await writer.write(encoder.encode("first\n"));
await writer.write(encoder.encode("second\n"));
await writer.close();
const output = await process.output();
return new TextDecoder().decode(output.stdout);
}
}Close the writer to send end-of-file (EOF). If you omit stdin, exec() closes standard input and sends EOF immediately.
RPC methods can accept byte-oriented ReadableStream values whose underlying source uses type: "bytes". A Request body meets this requirement. You can pass the received stream directly to exec() without buffering the entire stream in the Durable Object. For more information, refer to Streams over RPC.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async writeFile(input) {
const container = this.startContainer();
const process = await container.exec(["tee", "/tmp/upload.bin"], {
stdin: input,
stdout: "ignore",
});
return process.exitCode;
}
}
export default {
async fetch(request, env) {
if (!request.body) {
return new Response("Request body required", { status: 400 });
}
const container = env.MY_CONTAINER.getByName("upload-worker");
const exitCode = await container.writeFile(request.body);
return Response.json({ exitCode });
},
};import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async writeFile(input: ReadableStream<Uint8Array>) {
const container = this.startContainer();
const process = await container.exec(["tee", "/tmp/upload.bin"], {
stdin: input,
stdout: "ignore",
});
return process.exitCode;
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
if (!request.body) {
return new Response("Request body required", { status: 400 });
}
const container = env.MY_CONTAINER.getByName("upload-worker");
const exitCode = await container.writeFile(request.body);
return Response.json({ exitCode });
},
} satisfies ExportedHandler<Env>;RPC transfers ownership of the stream to the Durable Object. The calling Worker cannot read it after passing it to writeFile().
The following cat process exits because standard input is omitted:
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async verifyEndOfFile() {
const container = this.startContainer();
const process = await container.exec(["cat"]);
const output = await process.output();
return {
stdoutBytes: output.stdout.byteLength,
exitCode: output.exitCode,
};
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async verifyEndOfFile() {
const container = this.startContainer();
const process = await container.exec(["cat"]);
const output = await process.output();
return {
stdoutBytes: output.stdout.byteLength,
exitCode: output.exitCode,
};
}
}Use cwd, env, and user to set the process context. The process receives only the variables in env, plus PATH. It does not inherit other variables from the env option of start() or from the image. PATH comes from the env option of start(), or from the image when start() does not set it. To give a command a value that you passed to start(), pass it in the env option of exec() as well.
This example uses sh because it needs expansion and redirection. It also captures standard output and standard error separately.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async inspectWorkspace() {
const container = this.startContainer();
const process = await container.exec(
[
"sh",
"-c",
'printf "%s:%s:%s" "$PWD" "$MODE" "$EXTRA_VALUE"; printf "diagnostic" >&2',
],
{
cwd: "/workspace",
env: {
MODE: "inspection",
EXTRA_VALUE: "added",
},
},
);
const output = await process.output();
const decoder = new TextDecoder();
return {
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
};
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async inspectWorkspace() {
const container = this.startContainer();
const process = await container.exec(
[
"sh",
"-c",
'printf "%s:%s:%s" "$PWD" "$MODE" "$EXTRA_VALUE"; printf "diagnostic" >&2',
],
{
cwd: "/workspace",
env: {
MODE: "inspection",
EXTRA_VALUE: "added",
},
},
);
const output = await process.output();
const decoder = new TextDecoder();
return {
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
};
}
}The user option sets the numeric Linux user and group IDs for the process, as uid:gid. When omitted, the process runs as the image user. Before you rely on user to restrict a process, refer to exec().
Set stderr to "combined" to merge standard error into standard output. Combined output requires stdout: "pipe".
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async readCombinedOutput() {
const container = this.startContainer();
const process = await container.exec(
[
"bash",
"-lc",
'printf "standard output\n"; printf "standard error\n" >&2',
],
{
stdout: "pipe",
stderr: "combined",
},
);
const output = await process.output();
return new TextDecoder().decode(output.stdout);
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async readCombinedOutput() {
const container = this.startContainer();
const process = await container.exec(
[
"bash",
"-lc",
'printf "standard output\n"; printf "standard error\n" >&2',
],
{
stdout: "pipe",
stderr: "combined",
},
);
const output = await process.output();
return new TextDecoder().decode(output.stdout);
}
}The merged stream does not guarantee ordering between source streams. In this mode, process.stderr is undefined, and output.stderr is an empty ArrayBuffer. This example assumes Bash exists in the image.
A nonzero exit code resolves exitCode normally. It does not reject the promise.
This example preserves standard error while ignoring standard output:
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async runCheck() {
const container = this.startContainer();
const process = await container.exec(
[
"sh",
"-c",
'printf "not captured"; printf "check failed\n" >&2; exit 7',
],
{ stdout: "ignore" },
);
const output = await process.output();
return {
exitCode: output.exitCode,
stdoutBytes: output.stdout.byteLength,
stderr: new TextDecoder().decode(output.stderr),
};
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async runCheck() {
const container = this.startContainer();
const process = await container.exec(
[
"sh",
"-c",
'printf "not captured"; printf "check failed\n" >&2; exit 7',
],
{ stdout: "ignore" },
);
const output = await process.output();
return {
exitCode: output.exitCode,
stdoutBytes: output.stdout.byteLength,
stderr: new TextDecoder().decode(output.stderr),
};
}
}The result contains exit code 7 and the standard error text. Its ignored standard output buffer has zero bytes.
output() buffers both streams in memory. For large output, drain stdout and stderr concurrently instead.
import { DurableObject } from "cloudflare:workers";
async function countBytes(stream) {
if (!stream) {
return 0;
}
let bytes = 0;
for await (const chunk of stream) {
bytes += chunk.byteLength;
}
return bytes;
}
export class MyContainer extends DurableObject {
async generateLargeOutput() {
const container = this.startContainer();
const process = await container.exec([
"sh",
"-c",
'i=0; while [ "$i" -lt 100000 ]; do printf "output %s\n" "$i"; printf "error %s\n" "$i" >&2; i=$((i + 1)); done',
]);
const [stdoutBytes, stderrBytes, exitCode] = await Promise.all([
countBytes(process.stdout),
countBytes(process.stderr),
process.exitCode,
]);
return { stdoutBytes, stderrBytes, exitCode };
}
}import { DurableObject } from "cloudflare:workers";
async function countBytes(stream: ReadableStream<Uint8Array> | null) {
if (!stream) {
return 0;
}
let bytes = 0;
for await (const chunk of stream) {
bytes += chunk.byteLength;
}
return bytes;
}
export class MyContainer extends DurableObject<Env> {
async generateLargeOutput() {
const container = this.startContainer();
const process = await container.exec([
"sh",
"-c",
'i=0; while [ "$i" -lt 100000 ]; do printf "output %s\n" "$i"; printf "error %s\n" "$i" >&2; i=$((i + 1)); done',
]);
const [stdoutBytes, stderrBytes, exitCode] = await Promise.all([
countBytes(process.stdout),
countBytes(process.stderr),
process.exitCode,
]);
return { stdoutBytes, stderrBytes, exitCode };
}
}Streaming and output() are alternative consumption methods. output() throws a TypeError if either stream has started being consumed. A second call to output() also throws a TypeError.
Return a ReadableStream from an RPC method to stream output to the calling Worker. Combining standard error provides one stream for both output channels.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async streamCommandOutput() {
const container = this.startContainer();
const process = await container.exec(
["sh", "-c", 'printf "starting\n"; run-report'],
{ stderr: "combined" },
);
return process.stdout;
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async streamCommandOutput(): Promise<ReadableStream<Uint8Array>> {
const container = this.startContainer();
const process = await container.exec(
["sh", "-c", 'printf "starting\n"; run-report'],
{ stderr: "combined" },
);
return process.stdout!;
}
}RPC transfers ownership of the stream to the caller and preserves flow control. The caller must consume or cancel the stream. If the caller stops reading, backpressure can pause a process that continues writing.
This method transfers output, not the ExecProcess handle. Define a separate application protocol when the caller needs completion metadata or process control.
exec() has no built-in timeout. You can request termination after a delay with kill() and then await exitCode.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async runWithTimeout() {
const container = this.startContainer();
const process = await container.exec(["sleep", "120"]);
const timer = setTimeout(() => process.kill(), 30_000);
try {
return await process.exitCode;
} finally {
clearTimeout(timer);
}
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async runWithTimeout() {
const container = this.startContainer();
const process = await container.exec(["sleep", "120"]);
const timer = setTimeout(() => process.kill(), 30_000);
try {
return await process.exitCode;
} finally {
clearTimeout(timer);
}
}
}Calling kill() without an argument queues a SIGTERM, signal 15. You can pass another signal when the process requires it. A process can handle or ignore a signal, so this is not a hard execution deadline. Observe completion through exitCode, and do not infer a specific exit code from a signal.
kill() signals only the process that exec() started. Processes that this process starts, such as the commands in a bash -c script, keep running after exitCode resolves. output() waits until they exit.
To stop a command together with the processes it starts, run it under GNU coreutils timeout. The image must include timeout.
const process = await container.exec([
"timeout",
"--kill-after=5",
"30",
"bash",
"-c",
"npm test",
]);
const output = await process.output();
// 124 when the command times out, or 137 if timeout also sends SIGKILL.
console.log(output.exitCode);const process = await container.exec([
"timeout",
"--kill-after=5",
"30",
"bash",
"-c",
"npm test",
]);
const output = await process.output();
// 124 when the command times out, or 137 if timeout also sends SIGKILL.
console.log(output.exitCode);After 30 seconds, timeout sends SIGTERM to its process group. The group includes every process the command starts, unless a process moves to its own group, for example with setsid. With --kill-after=5, timeout sends SIGKILL to the group five seconds later if the command is still running.
Place exec() calls in the Durable Object that controls the container. The Durable Object can coordinate process state and container lifecycle.
One application RPC method can perform multiple exec() operations. Each command remains a separate exec operation, but the caller makes one Durable Object RPC call. This reduces caller-to-Durable Object round trips while keeping lifecycle decisions together.
import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject {
async runDiagnostics() {
const container = this.startContainer();
const commands = [
["uname", "-a"],
["node", "--version"],
];
const decoder = new TextDecoder();
const results = [];
for (const command of commands) {
const process = await container.exec(command);
const output = await process.output();
results.push({
command,
exitCode: output.exitCode,
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
});
}
return results;
}
}import { DurableObject } from "cloudflare:workers";
export class MyContainer extends DurableObject<Env> {
async runDiagnostics() {
const container = this.startContainer();
const commands = [
["uname", "-a"],
["node", "--version"],
];
const decoder = new TextDecoder();
const results = [];
for (const command of commands) {
const process = await container.exec(command);
const output = await process.output();
results.push({
command,
exitCode: output.exitCode,
stdout: decoder.decode(output.stdout),
stderr: decoder.decode(output.stderr),
});
}
return results;
}
}For all fields and return types, refer to the exec() API contract.