opensandbox沙箱服务器部署

98 阅读4分钟

opensandbox沙箱是什么?

opensandbox是阿里巴巴开发的专为AI应用场景设置沙箱平台,提供包含多语言 SDK、标准化沙盒协议和灵活运行时实现的完整解决方案。官网地址open-sandbox.ai/,github地址:github.com/alibaba/Ope…

如何部署opensandbox-server

opensandbox-server是什么?

opensandbox-server是一个基于 FastAPI 的服务,用于对沙箱容器的管理。主要提供提供的功能如下:

  1. 可插拔运行时 :Docker(生产准备)、Kubernetes(生产准备) -- 沙箱容器基于docker创建
  2. 异步配置 :后台创建以降低延迟
  3. 自动过期 :可配置 TTL 支持续费 -- 可配置容器的生命周期,续期
  4. 访问控制 :API 密钥认证 -- 可配置api-key
  5. 可观察性:带过渡日志的统一状态跟踪 -- 完整的日志系统

部署步骤

一、本地部署

  • 环境要求:Docker必要),Python 3.10+(推荐用于示例和本地运行时),uv环境
  • 运行步骤:
	git clone https://github.com/alibaba/OpenSandbox.git
	cd OpenSandbox/server
	uv sync
	cp example.config.toml ~/.sandbox.toml # Copy configuration file
	uv run python -m src.main # Start the service

或者使用以下命令(本人测试不一定成功,可能环境问题,上面的方式更保险

uv pip install opensandbox-server opensandbox-server init-config ~/.sandbox.toml --example docker

  • 修改.sandbox.toml配置文件(隐藏文件),默认位置 ~/.sandbox.toml
# Copyright 2025 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Example OpenSandbox configuration.
# Copy this file to ~/.sandbox.toml or set SANDBOX_CONFIG_PATH to point at it.
# Each top-level block mirrors the sections supported by src/config.py.

[server]
# Lifecycle API host/port and logging settings
# -----------------------------------------------------------------
host = "0.0.0.0"  # 服务ip
port = 8090       # 服务端口

log_level = "INFO"

# API 密钥认证
api_key = "haizhi123"

[storage]
# 允许进行 bind mount 的宿主机路径前缀白名单。
# 仅匹配这些前缀的路径才能被挂载到沙箱中。
# 如果为空,则允许所有路径(不建议在生产环境使用)。
allowed_host_paths = ["/tmp/opensandbox-data", "/data/shared"]

[runtime]
# 运行选择 (docker | kubernetes)
# -----------------------------------------------------------------
type = "docker"
execd_image = "opensandbox/execd:v1.0.5"
egress_image = "opensandbox/egress:v1.0.0"

[docker]
# Docker-specific knobs
# -----------------------------------------------------------------
# Use bridge for network isolation
network_mode = "bridge"
# Drop dangerous capabilities and block privilege escalation
drop_capabilities = ["AUDIT_WRITE", "MKNOD", "NET_ADMIN", "NET_RAW", "SYS_ADMIN", "SYS_MODULE", "SYS_PTRACE", "SYS_TIME", "SYS_TTY_CONFIG"]
no_new_privileges = true
# Optional: set an AppArmor profile name (e.g., "docker-default") when AppArmor is enabled
apparmor_profile = ""
# Limit process count to reduce host impact from fork bombs; set to null to disable
pids_limit = 512
# Seccomp profile: empty string uses Docker default; set to an absolute path for a custom profile
seccomp_profile = ""

  • 启动命令:opensandbox-server

二、Docker部署(推荐)

  • 前期准备:docker镜像 sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/server ,yaml文件 docker-compose.example.yaml用于构建docker容器,位置在 openSandbox/server/docker-compose.example.yaml
  • 修改docker-compose.example.yaml
configs:
  opensandbox-config:
    content: |
      [server]
      host = "0.0.0.0"
      # opensandbox-server对外端口
      port = 8090 
      log_level = "INFO"

      [runtime]
      type = "docker"
      execd_image = "sandbox-registry.cn-zhangjiakou.cr.aliyuncs.com/opensandbox/execd:v1.0.6"

      [egress]
      image = "opensandbox/egress:v1.0.3"

      [docker]
      network_mode = "bridge"
      host_ip = "host.docker.internal" #如果是docker部署最好换成宿主机IP
      drop_capabilities = ["AUDIT_WRITE", "MKNOD", "NET_ADMIN", "NET_RAW", "SYS_ADMIN", "SYS_MODULE", "SYS_PTRACE", "SYS_TIME", "SYS_TTY_CONFIG"]
      no_new_privileges = true
      pids_limit = 512

      [ingress]
      mode = "direct"

version: '3.8'

services:
  opensandbox-server:
    image: opensandbox/server:latest     # 基于的镜像
    container_name: opensandbox-server   # 容器的名称
    networks:
      - opensandbox-net
    ports:
      - "8090:8090" #根据实际情况设置
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock #重要,是opensandbox-server操作docker沙箱的基本
    configs:
      - source: opensandbox-config
        target: /etc/opensandbox/config.toml
    environment:
      - SANDBOX_CONFIG_PATH=/etc/opensandbox/config.toml

  # 可以删除,用于测试的客户端
  sdk-client:
    image: python:3.11-slim
    container_name: sdk-client
    networks:
      - opensandbox-net
    command: >
      sh -c "pip install opensandbox && tail -f /dev/null"
    environment:
      - OPENSANDBOX_SERVER_URL=http://opensandbox-server:8090

networks:
  opensandbox-net:
    driver: bridge
  • docker-compose.example.yaml同级目录下执行docker-compose up -d即可

Kotlin or java SDK

一、环境准备

  • 环境:java 17springboot 3.2.4kotlin 2.2.0+Intellij Ideal 2025
  • maven依赖(主要依赖):
 <!-- springboot兼容kotlin需要导入 -->
 <dependency>  
    <groupId>org.jetbrains.kotlin</groupId>  
    <artifactId>kotlin-stdlib</artifactId>  
    <version>1.8.22</version>  
</dependency>  
<dependency>  
    <groupId>org.jetbrains.kotlin</groupId>  
    <artifactId>kotlin-reflect</artifactId>  
    <version>1.8.22</version>  
</dependency>
 
 <!-- opensandbox依赖 -->
  <dependency>  
    <groupId>com.alibaba.opensandbox</groupId>  
    <artifactId>sandbox</artifactId>  
    <version>1.0.4</version>  
    <scope>compile</scope>  
</dependency>  
<!-- opensandbox依赖 -->
<dependency>  
    <groupId>com.alibaba.opensandbox</groupId>  
    <artifactId>sandbox-api</artifactId>  
    <version>1.0.4</version>  
    <scope>compile</scope>  
</dependency>  
<!-- opensandbox 依赖 -->
<dependency>  
    <groupId>com.alibaba.opensandbox</groupId>  
    <artifactId>code-interpreter</artifactId>  
    <version>1.0.4</version>  
</dependency>

注意!Intellij Idealkotlin版本必须是2.2.0+,否则编辑器无法识别!!!

二、代码示例

Quick Start  快速入门

import com.alibaba.opensandbox.sandbox.Sandbox;
import com.alibaba.opensandbox.sandbox.config.ConnectionConfig;
import com.alibaba.opensandbox.sandbox.domain.exceptions.SandboxException;
import com.alibaba.opensandbox.sandbox.domain.models.execd.executions.Execution;

public class QuickStart {
    public static void main(String[] args) {
        // 1. 连接配置
        ConnectionConfig config = ConnectionConfig.builder()
            .domain("api.opensandbox.io")
            .apiKey("your-api-key")
            .build();

        // 2. 沙箱基本信息
        try (Sandbox sandbox = Sandbox.builder()
                .connectionConfig(config)
                .image("ubuntu")
                .build()) {

            // 3. 执行命令
            Execution execution = sandbox
                    .commands()
                    .run("echo 'Hello Sandbox!'");

            // 4. 打印结果
            System.out.println(execution.getLogs().getStdout().get(0).getText());

            // 5. 关闭沙箱
            sandbox.kill();
        } catch (SandboxException e) {
            // Handle Sandbox specific exceptions
            System.err.println("Sandbox Error: [" + e.getError().getCode() + "] " + e.getError().getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

其他操作示例,请见:github.com/alibaba/Ope… 目录挂载,请见:github.com/alibaba/Ope…