每个沙箱都可以访问互联网,并且可被公共 URL 访问其上运行的服务。

沙箱公共 URL

每个沙箱都能提供公共 URL,用于访问沙箱内运行的服务。

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

// 您需要传入一个端口号来获取公共 URL。
const host = sandbox.getHost(3000)
console.log(`https://${host}`)

// 输出示例:
// https://3000-icl2ke7w1grxep2o771m1-abf219fd.sandbox.ppio.cn

访问沙箱内运行的服务

您可以在沙箱内启动服务并通过一个公共 URL 访问它。

在这个示例中,我们将启动一个简单的 HTTP 服务器,监听端口 3000,并返回启动服务器的目录信息。

import { Sandbox } from '@e2b/code-interpreter'

const sandbox = await Sandbox.create()

// 启动一个简单的 HTTP 服务器。
const process = await sandbox.commands.run('python -m http.server 3000', { background: true })
const host = sandbox.getHost(3000)
const url = `https://${host}`
console.log('Server started at:', url)

// 从服务器获取数据。
const response = await fetch(url);
const data = await response.text();
console.log('Response from server inside sandbox:', data);

// 终止服务器进程。
await process.kill()

// 输出示例:
// Server started at: https://3000-is4mc1846qdhvdu6lfwep-2b677fa8.sandbox.ppio.cn
// Response from server inside sandbox: <!DOCTYPE HTML>
// <html lang="en">
// <head>
// <meta charset="utf-8">
// <title>Directory listing for /</title>
// </head>
// <body>
// <h1>Directory listing for /</h1>
// <hr>
// <ul>
// <li><a href=".bash_logout">.bash_logout</a></li>
// <li><a href=".bashrc">.bashrc</a></li>
// <li><a href=".profile">.profile</a></li>
// </ul>
// <hr>
// </body>
// </html>