Skip to content

Ports

A port of a sandbox is reached from the host once it is published on a port of the host. This page covers the ports published from the start, those published on a running sandbox, and how a server in a sandbox is reached.

docs_src/client/ports.py
import fastsandbox
from fastsandbox.models import PortBinding


async def main() -> None:
    client = await fastsandbox.connect()
    # Published from the start, and again at every start.
    web = PortBinding.tcp(8000, 48000)
    async with client.create(kit="shell", ports=[web]) as sandbox, sandbox.running():
        for port in await sandbox.ports():
            print(f"{port.host_ip or '127.0.0.1'}:{port.host_port} -> {port.sandbox_port}")

        # Published on the running sandbox, then taken back.
        published = await sandbox.publish(PortBinding.tcp(9000, 49000, host_ip="127.0.0.1"))
        print(f"published: {[port.host_port for port in published]}")
        await sandbox.unpublish(*published)


if __name__ == "__main__":
    fastsandbox.run(main())

Bindings

A PortBinding maps a sandbox_port to a host_port: PortBinding.tcp(sandbox_port, host_port) or PortBinding.udp(...). The daemon binds the host port on 127.0.0.1 unless host_ip says otherwise.

Published from the start

The ports of client.create() are part of the desired configuration of the sandbox: they are published when it starts, and again at every start. replace_desired_port(old, new) changes one of them for the next start, leaving the ports published now as they are; an old binding that is not part of the desired configuration raises NotFoundError.

Published on a running sandbox

  • publish(*ports) publishes ports and returns the bindings the daemon applied. A stopped sandbox, or a host port already taken, raises ConflictError.
  • unpublish(*ports) takes them back; a port that is not published is ignored.
  • ports() lists the ports published now.

Reaching a server

A server in a sandbox runs as an interactive session, which keeps it running until it exits or the sandbox goes; exec() would wait for its end. Read its output until it says it listens, then publish its port:

server = await sandbox.attach(["python3", "-u", "-m", "http.server", "8000"])
started = ""
async for chunk in server:  # "Serving HTTP on 0.0.0.0 port 8000 ..."
    started += chunk.text
    if "Serving HTTP" in started:
        break
published = await sandbox.publish(PortBinding.tcp(8000, 48000))

The loop also ends when the server exits before it listens, and waits for as long as it says nothing: check started after it, and bound the wait with asyncio.timeout(). Right after the publication, a connection to the host port may still be refused or reset: retry it for a few seconds. The shell-ports example serves a page from a sandbox this way, with both checks (see Examples).