通过 Ajax 使用 docker 执行沙箱命令

Sandbox command execution with docker via Ajax

我正在寻求这方面的帮助,如果我想对在网站中键入的命令的执行进行沙盒处理,我有哪些选择?我想为一种编程语言创建一个在线解释器。

我一直在看docker,我该如何使用它?这是最好的选择吗?

codecube.io does this. It's open source: https://github.com/hmarr/codecube

作者写了他的rationale and process。以下是系统的工作原理:

  • A user types some code in to a box on the website, and specifies the language the code is written in
  • They click “Run”, the code is POSTed to the server
  • The server writes the code to a temporary directory, and boots a docker container with the temporary directory mounted
  • The container runs the code in the mounted directory (how it does this varies according to the code’s language)
  • The server tails the logs of the running container, and pushes them down to the browser via server-sent events
  • The code finishes running (or is killed if it runs for too long), and the server destroys the container

Docker 容器的入口点是 entrypoint.sh,它在容器内运行:

prog=
<...create user and set permissions...>
sudo -u codecube /bin/bash /run-code.sh $prog

然后run-code.sh检查扩展并运行相关的编译器或解释器:

extension="${prog##*.}"
case "$extension" in
  "c")
    gcc $prog && ./a.out
    ;;
  "go")
    go run $prog
    ;;
<...cut...>

The server that accepts the code examples from the web, and orchestrates the Docker containers was written in Go. Go turned out to be a pretty good choice for this, as much of the server relied on concurrency (tailing logs to the browser, waiting for containers to die so cleanup could happen), which Go makes joyfully simple.

作者还详细介绍了他是如何实现资源限制、隔离和安全思想的。