AI Code Interpreter 与代码沙箱深度实战 - 4. Docker 容器沙箱
本文是 AI Code Interpreter 与代码沙箱深度实战 的分章阅读版。
4. Docker 容器沙箱
4.1 Docker 沙箱的安全配置
@Service
public class DockerSandboxService implements CodeSandboxService {
private static final String SANDBOX_IMAGE = "python:3.11-slim";
private static final Duration EXEC_TIMEOUT = Duration.ofSeconds(30);
private static final long MEM_LIMIT_MB = 512;
private static final double CPU_LIMIT = 1.0;
@Override
public CodeExecutionResult execute(String code, Language language,
ExecutionConfig config) {
// 1. 写代码到临时文件
Path codeFile = writeCodeToTemp(code, language);
// 2. 构建 docker run 命令
List<String> cmd = buildSecureDockerCommand(codeFile, language, config);
// 3. 执行
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
try {
Process process = pb.start();
// 4. 设置超时
ByteArrayOutputStream output = new ByteArrayOutputStream();
CompletableFuture<Integer> future = process.onExit()
.thenApply(Process::exitValue);
try {
int exitCode = future.get(EXEC_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
output.write(process.getInputStream().readAllBytes());
return new CodeExecutionResult(exitCode, output.toString(), "");
} catch (TimeoutException e) {
process.destroyForcibly();
return CodeExecutionResult.timeout("Execution exceeded " + EXEC_TIMEOUT);
}
} finally {
// 5. 清理临时文件
Files.deleteIfExists(codeFile);
}
}
private List<String> buildSecureDockerCommand(Path codeFile, Language lang,
ExecutionConfig config) {
return List.of(
"docker", "run", "--rm",
// 内存限制
"--memory", MEM_LIMIT_MB + "m",
"--memory-swap", MEM_LIMIT_MB + "m", // 禁止 swap
// CPU 限制
"--cpus", String.valueOf(CPU_LIMIT),
"--cpu-shares", "512",
// 进程限制
"--pids-limit", "50",
// 文件系统
"--read-only", // 根文件系统只读
"--tmpfs", "/tmp:rw,size=64m", // 仅 /tmp 可写,64MB 上限
// 网络
"--network", config.networkEnabled() ? "bridge" : "none",
// 用户
"--user", "1000:1000", // 非 root
// 权限
"--cap-drop", "ALL", // 移除所有 Linux capabilities
"--security-opt", "no-new-privileges",
"--security-opt", "seccomp=/etc/docker/seccomp-strict.json",
"--security-opt", "apparmor=docker-strict",
// 超时
"--stop-timeout", "5",
// 文件挂载
"-v", codeFile.toAbsolutePath() + ":/code/" + codeFile.getFileName() + ":ro",
// 工作目录
"-w", "/code",
// 镜像
SANDBOX_IMAGE,
// 执行命令
lang.command(), codeFile.getFileName().toString()
);
}
}
public enum Language {
PYTHON("python"),
NODE("node"),
JAVA("java"),
GO("go"),
RUST("rustc");
private final String command;
Language(String command) { this.command = command; }
public String command() { return command; }
}
public record ExecutionConfig(
boolean networkEnabled,
Duration timeout,
long memoryLimitMB,
Map<String, String> envVars
) {}
4.2 Seccomp 严格配置
{
"defaultAction": "SCMP_ACT_ERRNO",
"syscalls": [
{
"names": [
"read", "write", "open", "openat", "close", "stat", "fstat", "lstat",
"mmap", "mprotect", "munmap", "brk", "rt_sigaction", "rt_sigprocmask",
"ioctl", "pread64", "pwrite64", "readv", "writev", "access", "pipe",
"select", "sched_yield", "mremap", "msync", "mincore", "madvise",
"shmget", "shmat", "shmctl", "shmdt", "dup", "dup2", "pause",
"nanosleep", "getitimer", "alarm", "setitimer", "getpid", "sendfile",
"socket", "connect", "listen", "accept", "bind", "setsockopt",
"getsockopt", "recvfrom", "sendto", "shutdown"
],
"action": "SCMP_ACT_ALLOW"
},
{
"names": [
"fork", "vfork", "clone", "clone3",
"execve", "execveat",
"ptrace", "process_vm_readv", "process_vm_writev",
"mount", "umount", "umount2",
"reboot", "init_module", "finit_module", "delete_module",
"kexec_load", "kexec_file_load",
"iopl", "ioperm",
"setuid", "setgid", "setreuid", "setregid", "setresuid", "setresgid"
],
"action": "SCMP_ACT_ERRNO"
}
]
}
4.3 容器预热池
@Component
public class WarmContainerPool {
private final ConcurrentLinkedQueue<ContainerInstance> pool = new ConcurrentLinkedQueue<>();
private static final int POOL_SIZE = 10;
private static final int MAX_IDLE_SECONDS = 300;
@PostConstruct
public void warmUp() {
for (int i = 0; i < POOL_SIZE; i++) {
pool.offer(createContainer());
}
}
public ContainerInstance acquire() {
ContainerInstance c = pool.poll();
if (c == null || c.isExpired()) {
if (c != null) c.destroy();
c = createContainer();
}
return c;
}
public void release(ContainerInstance container) {
if (container.isExpired() || container.execCount() > 50) {
container.destroy();
} else {
pool.offer(container);
// 补充池
if (pool.size() < POOL_SIZE) {
CompletableFuture.runAsync(this::createContainerAsync);
}
}
}
private ContainerInstance createContainer() {
// 启动一个保持运行的容器
// docker run -d --rm ... python:3.11 sleep infinity
// ...
return null;
}
}
相关页面