@ computesdk/ docker (帮助)
基于 Docker 的提供者 计算SDK 发射轻量级,可配置的容器(Python或Node.js),运行代码和 shell 命令,并提供简单的文件系统辅助器件——全部在干净的提供者-不可知界面后.
安装
# like the other computesdk providers — single package
pnpm add @computesdk/docker
# or
npm i @computesdk/docker
# or
yarn add @computesdk/docker
你个 对 在此运行的主机上需要一个正在工作的多克引擎/ 守护进程 .
设置
除了Docker没什么特别的 提供商和多克通过 dockerode,它自动检测您从env或默认的套接字连接.
常见的环境变量(被多克/多克罗得所使用) :
DOCKER_HOST- 比如说.unix:///var/run/docker.sock(Linux/macOS)或 缩写tcp://127.0.0.1:2375DOCKER_TLS_VERIFY, (中文(简体) ),DOCKER_CERT_PATH——用于TLS安全TCPHTTP_PROXY, (中文(简体) ),HTTPS_PROXY, (中文(简体) ),NO_PROXY——因为牵引后代理
在 Linux 上,确保您的用户能够访问 Docker :
sudo usermod -aG docker $USER然后重新登录,或用sudo。 。 。 .
使用量
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();
高级配置
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();
配置
类型 : 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;
}
默认( 摘录 ) :
{
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 },
},
}
环境变量
- 连接变量从 设置
- 您的工作量通过
container.env(注入容器)
特征
- 蟒 财务报告和审定财务报表 节点.js 运行时间
- 代码执行 带有语法错误的表面
- 贝壳命令 (带有 PID 的前置背景( B))
- 文件系统助手数字 :
readFile, (中文(简体) ),writeFile, (中文(简体) ),mkdir, (中文(简体) ),readdir, (中文(简体) ),exists, (中文(简体) ),remove - 端口 URL 分辨率数字 :
getUrl({ port })+ 如果发布主机 URL - 输入访问数字 :
getInstance()返回居中点Container和客户端 - 图像拉动策略数字 :
always | ifNotPresent | never(+ 登记认证)
API 参考
命令执行
sandbox.runCommand(command: string, options?: RunCommandOptions): Promise<CommandResult>
- 运行通过
/bin/sh -c "…"与stdout/stder抓取. - 回返
{ stdout, stderr, exitCode, durationMs }。 。 。 . - 选项 :
{ cwd?, env?, timeout?, background? }。 。 。 .
文件系统操作
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)
通过外壳+基质64执行可移植性.
终端操作
互动终端没有曝光。 使用 runCommand('…') 非交互式会议.
沙盒管理
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();
处理错误
- 命令错误 + 作为非零返回
exitCode与stderr - Docker 错误 (推/起/执行) 抛出
const res = await sb.runCommand('bad-command');
if (res.exitCode !== 0) {
console.error('stderr:', res.stderr);
}
实例
数据科学工作流程( 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();
状态循环
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();
背景进程 + 端口
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();
要让端口从主机到达,请在站前公布:
const compute = docker({ runtime: 'python', image: { name: 'python:3.11-slim' }, container: { ports: { '8080/tcp': [{ hostPort: 8080, hostIP: '127.0.0.1' }] }, }, });
最佳做法
- CI 中的预推图像 :
docker pull python:3.11-slim node:20-alpine - Pin 图像版本; 避免
latest - 设定
container.resources绑定 CPU/RAM - 使用
/workspace并保存临时文件/tmp - 发布您打算通过
getUrl() - 优先无根
user并减少不必要的能力 - 对于 GPU 工作 :
gpus: 'all',并确保 NVIDIA 运行时间/驱动器
限制
- 需要本地或可达到的 Docker 守护进程
- 无 WebSocket 终端( 仅非交互)
- 此提供者未执行的快照/ 模板
getUrl()返回只针对已发布端口或可到达的容器IP的主机 URL
支助
- 问题/PRs: https://github.com/computesdk/computesdk 页面存档备份,存于互联网档案馆
- 带有标题前缀的打开问题 [打
许可证
麻省理工学院