@computesdk/docker

中文文档
1.2.68发布于 2026/11/06MITTypeScriptESM + CJS构建来源已验证近 30 天下载 3995

Docker provider for ComputeSDK - local containerized sandboxes for development and testing

原始使用文档
文档目录21 节
  1. Installation
  2. Setup
  3. Usage
  4. Advanced Configuration
  5. Configuration
  6. Environment Variables
  7. Features
  8. API Reference
  9. Command Execution
  10. Filesystem Operations
  11. Terminal Operations
  12. Sandbox Management
  13. Error Handling
  14. Examples
  15. Data Science Workflow (Python)
  16. Stateful Loop
  17. Background Process + Ports
  18. Best Practices
  19. Limitations
  20. Support
  21. License

@computesdk/docker

A Docker-based provider for ComputeSDK that launches lightweight, configurable containers (Python or Node.js), runs code and shell commands, and offers simple filesystem helpers — all behind a clean, provider-agnostic interface.


Installation

# like the other computesdk providers — single package
pnpm add @computesdk/docker
# or
npm i @computesdk/docker
# or
yarn add @computesdk/docker

You do need a working Docker Engine/Daemon on the host where this runs.


Setup

Nothing special beyond Docker. The provider talks to Docker through dockerode, which autodetects your connection from env or the default socket.

Common environment variables (used by Docker/dockerode):

  • DOCKER_HOST — e.g. unix:///var/run/docker.sock (Linux/macOS) or tcp://127.0.0.1:2375
  • DOCKER_TLS_VERIFY, DOCKER_CERT_PATH — for TLS-secured TCP
  • HTTP_PROXY, HTTPS_PROXY, NO_PROXY — for pulls behind a proxy

On Linux, ensure your user can access Docker: sudo usermod -aG docker $USER then re-login, or run with sudo.


Usage

import { docker } from '@computesdk/docker';

const compute = docker({
  runtime: 'python', // or 'node'
  image: { name: 'python:3.11-slim', pullPolicy: 'ifNotPresent' },
});

// Create a sandbox and run Python
const sandbox = await compute.instances.create();
const result = await sandbox.runCommand('python -c "print(\"Hello from Python\")"');
console.log(result.stdout.trim()); // Hello from Python

await sandbox.destroy();

Advanced Configuration

import { docker } from '@computesdk/docker';

const compute = docker({
  runtime: 'node',
  image: { name: 'node:20-alpine' },
  container: {
    workdir: '/workspace',
    env: { FOO: 'bar' },
  },
});

const sandbox = await compute.instances.create();

const result = await sandbox.runCommand('node -e "console.log(\"Hello, World!\")"');
console.log(result.stdout.trim()); // Hello, World!

const cmd = await sandbox.runCommand('echo Hello from command');
console.log(cmd.stdout.trim()); // Hello from command

await sandbox.destroy();

Configuration

Type: DockerConfig

{
  // dockerode connection; if omitted, dockerode uses DOCKER_HOST or /var/run/docker.sock
  connection?: import('dockerode').DockerOptions;

  // default runtime; must be 'python' or 'node'
  runtime?: 'python' | 'node';

  // provider-side execution timeout (ms)
  timeout?: number;

  // image to use for containers
  image: {
    name: string;                   // e.g. 'python:3.11-slim' or 'node:20-alpine'
    pullPolicy?: 'always' | 'ifNotPresent' | 'never';
    auth?: { username?: string; password?: string; serveraddress?: string; identitytoken?: string; registrytoken?: string; };
  };

  // container defaults
  container?: {
    user?: string;
    workdir?: string;
    env?: Record<string, string>;
    binds?: string[];               // ['/host:/container:ro']
    ports?: Record<`${number}/${'tcp'|'udp'}`, Array<{ hostPort?: number; hostIP?: string }>>;
    networkMode?: string;           // 'bridge', 'host', custom
    privileged?: boolean;
    capabilities?: { add?: string[]; drop?: string[] };
    gpus?: 'all' | number | string; // requires NVIDIA runtime/drivers
    resources?: { memory?: number; nanoCPUs?: number; cpuShares?: number; /* … */ };
    logDriver?: string;
    logOpts?: Record<string, string>;
    autoRemove?: boolean;           // default true
    tty?: boolean;
    openStdin?: boolean;
  };

  // raw passthrough if you need full control
  createOptions?: import('dockerode').ContainerCreateOptions;
  startOptions?: import('dockerode').ContainerStartOptions;

  cleanup?: 'always' | 'onSuccess' | 'never';
  streamLogs?: boolean;
}

Defaults (excerpt):

{
  runtime: 'python',
  image: { name: 'python:3.11-slim', pullPolicy: 'ifNotPresent' },
  container: {
    workdir: '/workspace',
    env: {},
    autoRemove: true,
    tty: false,
    openStdin: false,
    resources: { memory: 512 * 1024 * 1024 },
  },
}

Environment Variables

  • Docker connection variables from Setup
  • Your workload envs via container.env (injected into the container)

Features

  • Python and Node.js runtimes
  • Code execution with syntax-error surfacing
  • Shell commands (foreground & background with PID)
  • Filesystem helpers: readFile, writeFile, mkdir, readdir, exists, remove
  • Port URL resolution: getUrl({ port }) → host URL if published
  • Typed access: getInstance() returns the dockerode Container and client
  • Image pull policy: always | ifNotPresent | never (+ registry auth)

API Reference

Command Execution

sandbox.runCommand(command: string, options?: RunCommandOptions): Promise<CommandResult>
  • Runs via /bin/sh -c "…" with stdout/stderr capture.
  • Returns { stdout, stderr, exitCode, durationMs }.
  • Options: { cwd?, env?, timeout?, background? }.

Filesystem Operations

sandbox.filesystem.readFile(path)
sandbox.filesystem.writeFile(path, content)
sandbox.filesystem.mkdir(path)
sandbox.filesystem.readdir(path)
sandbox.filesystem.exists(path)
sandbox.filesystem.remove(path)

Implemented via shell + base64 for portability.

Terminal Operations

Interactive terminals aren’t exposed. Use runCommand('…') for non-interactive sessions.

Sandbox Management

const sandbox = await compute.instances.create();

await sandbox.getInfo(); // { id, provider, status, createdAt, timeout, metadata }
await sandbox.getUrl({ port, protocol?: 'http' | 'https' });
sandbox.getInstance(); // { docker: Docker, container: Container, ... }
await sandbox.destroy();

Error Handling

  • Command errors → returned as non-zero exitCode with stderr
  • Docker errors (pull/start/exec) → thrown
const res = await sb.runCommand('bad-command');
if (res.exitCode !== 0) {
  console.error('stderr:', res.stderr);
}

Examples

Data Science Workflow (Python)

const sandbox = await compute.instances.create();
await sandbox.runCommand('python3 -m pip install --no-cache-dir pandas');
await sandbox.filesystem.writeFile('/workspace/app.py', `
import pandas as pd
print("rows:", len(pd.DataFrame({"x":[1,2,3]})))
`);
const run = await sandbox.runCommand('python3 /workspace/app.py');
console.log(run.stdout.trim()); // rows: 3
await sandbox.destroy();

Stateful Loop

const sandbox = await compute.instances.create();
await sandbox.runCommand('echo boot > /tmp/state');
const res = await sandbox.runCommand('cat /tmp/state'); // 'boot'
await sandbox.destroy();

Background Process + Ports

const sandbox = await compute.instances.create();
await sandbox.runCommand('python3 -m http.server 8080', { background: true });
const url = await sandbox.getUrl({ port: 8080 });
console.log('Serving at', url);
await sandbox.destroy();

To make ports reachable from the host, publish them up front:

const compute = docker({
  runtime: 'python',
  image: { name: 'python:3.11-slim' },
  container: {
    ports: { '8080/tcp': [{ hostPort: 8080, hostIP: '127.0.0.1' }] },
  },
});

Best Practices

  • Pre-pull images in CI: docker pull python:3.11-slim node:20-alpine
  • Pin image versions; avoid latest
  • Set container.resources to bound CPU/RAM
  • Use /workspace and keep temp files in /tmp
  • Publish ports you intend to access via getUrl()
  • Prefer non-root user and drop unnecessary capabilities
  • For GPU work: gpus: 'all' and ensure NVIDIA runtime/drivers

Limitations

  • Requires a local or reachable Docker daemon
  • No WebSocket terminal (non-interactive only)
  • Snapshots/templates not implemented in this provider
  • getUrl() returns a host URL only for published ports or reachable container IPs

Support


License

MIT

版本与发布记录

@computesdk/docker 共发布 82 个版本,首次发布于 2025/10/15;过去 12 个月发布了 78 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.2.68latest2026/11/064 天前
1.2.672026/11/046 天前
1.2.662026/10/2813 天前
1.2.652026/10/2318 天前
1.2.642026/10/2318 天前
1.2.632026/10/2219 天前

关于 @computesdk/docker 的常见问题

@computesdk/docker 是什么?

Docker provider for ComputeSDK - local containerized sandboxes for development and testing

如何安装 @computesdk/docker?

在项目目录运行 npm install @computesdk/docker,或使用 pnpm add / yarn add / bun add。

@computesdk/docker 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@computesdk/docker 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@computesdk/docker 可以商用吗?

@computesdk/docker 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@computesdk/docker 的下载量有多少?

根据 npm 官方下载统计,@computesdk/docker 在 2026/10/11 – 2026/11/09 这 30 天内被下载 3,995 次,日均约 133 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@computesdk/docker 还在维护吗?

最新版本 1.2.68 发布于 2026/11/06(4 天前);至今共发布 82 个版本,其中过去 12 个月发布了 78 个;首次发布于 2025/10/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。