跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

运行 Linux 命令

最后更新 查看 MarkdownAgent 设置

你将向 Worker POST uname -a,并读取包含 Linux 的 stdout。

前提条件

  1. 注册 Cloudflare 账户 ↗。
  2. 安装 Node.js ↗。

Node.js 版本管理器

使用 Vite+ (vp env) ↗ 安装和管理 Node.js 版本。

有关支持的 Node.js 版本,请参阅 Wrangler 系统要求。

在 Linux 中运行命令

  1. 创建一个 Worker 项目:

    npm create cloudflare@latest -- sandbox-linux --category=hello-world --type=hello-world --lang=ts --no-deploy --no-git --no-agents
  2. 进入项目目录:

    cd sandbox-linux
  3. 替换 wrangler.jsonc,使 Durable Object 能够启动 container:

    {
        "$schema": "node_modules/wrangler/config-schema.json",
        "name": "sandbox-linux",
        "main": "src/index.ts",
        // Set this to today's date
        "compatibility_date": "2026-11-14",
        "observability": {
            "enabled": true,
        },
        "upload_source_maps": true,
        "containers": [
            {
                "class_name": "MyContainer",
                "scheduling_policy": "durable_object",
            },
        ],
        "durable_objects": {
            "bindings": [
                {
                    "class_name": "MyContainer",
                    "name": "MY_CONTAINER",
                },
            ],
        },
        "exports": {
            "MyContainer": {
                "type": "durable-object",
                "storage": "sqlite",
            },
        },
    }
    "$schema" = "node_modules/wrangler/config-schema.json"
    name = "sandbox-linux"
    main = "src/index.ts"
    # Set this to today's date
    compatibility_date = "2026-11-14"
    upload_source_maps = true
    
    [observability]
    enabled = true
    
    [[containers]]
    class_name = "MyContainer"
    scheduling_policy = "durable_object"
    
    [[durable_objects.bindings]]
    class_name = "MyContainer"
    name = "MY_CONTAINER"
    
    [exports.MyContainer]
    type = "durable-object"
    storage = "sqlite"
  4. 替换 src/index.ts。Worker 会从 JSON 正文读取 argv,并在 Linux 中运行它:

    src/index.jsjs
    import { DurableObject } from "cloudflare:workers";
    
    export class MyContainer extends DurableObject {
    	async exec(argv) {
    		const container = this.ctx.container;
    		if (!container) {
    			throw new Error("No container is configured");
    		}
    
    		if (!container.running) {
    			container.start({
    				// Debian Trixie with Node.js 24
    				image: "cloudflare/debian-trixie",
    				// Keep the instance running so it can accept commands
    				entrypoint: ["sleep", "infinity"],
    				// Block commands in the sandbox from reaching the Internet
    				enableInternet: false,
    			});
    		}
    
    		const process = await container.exec(argv);
    		const output = await process.output();
    		return {
    			stdout: new TextDecoder().decode(output.stdout),
    			exitCode: output.exitCode,
    		};
    	}
    }
    
    export default {
    	async fetch(request, env) {
    		const { argv } = await request.json();
    		const sandbox = env.MY_CONTAINER.getByName("sandbox");
    		return Response.json(await sandbox.exec(argv));
    	},
    };
    src/index.tsts
    import { DurableObject } from "cloudflare:workers";
    
    export class MyContainer extends DurableObject<Env> {
        async exec(argv: string[]) {
            const container = this.ctx.container;
            if (!container) {
                throw new Error("No container is configured");
            }
    
            if (!container.running) {
                container.start({
                    // Debian Trixie with Node.js 24
                    image: "cloudflare/debian-trixie",
                    // Keep the instance running so it can accept commands
                    entrypoint: ["sleep", "infinity"],
                    // Block commands in the sandbox from reaching the Internet
                    enableInternet: false,
                });
            }
    
            const process = await container.exec(argv);
            const output = await process.output();
            return {
                stdout: new TextDecoder().decode(output.stdout),
                exitCode: output.exitCode,
            };
        }
    }
    
    export default {
        async fetch(request: Request, env: Env): Promise<Response> {
            const { argv } = (await request.json()) as { argv: string[] };
            const sandbox = env.MY_CONTAINER.getByName("sandbox");
            return Response.json(await sandbox.exec(argv));
        },
    };
  5. 为绑定生成类型。Wrangler 会从 src/index.ts 读取 MyContainer 类,以便为 env.MY_CONTAINER 提供类型:

    npx wrangler types
  6. 运行 wrangler dev:

    npx wrangler dev

    wrangler dev 会在你机器上的 Docker ↗ 中运行该实例,因此 Docker 必须正在运行。在本地运行 cloudflare/debian-trixie 需要 Wrangler 4.141.0 或更高版本。

  7. 向 Wrangler 打印的 URL POST 一条命令。默认是 http://localhost:8787:

    curl http://localhost:8787 --request POST --json '{"argv":["uname","-a"]}'

JSON 正文中包含 "exitCode":0。stdout 包含 Linux。Worker 启动了 Linux 容器,并运行你发送的命令。部署后,每个实例都会在自己的虚拟机中运行,而不是在 Docker 中运行。

后续步骤

这篇文档对您有帮助吗?