English
Docs menu

Agent Sandboxes docs · Tasks

Ports and previews: a sandbox's URLs

Updated · 6 min read

Every port of a sandbox has an HTTPS address of its own, https://<port>-<sandbox id>.<server>. Make a port public and anyone can open it; leave it private and it answers only requests that carry its token. A request to a paused sandbox's port wakes it, so a preview can sleep between visits.

In short
  • wait_for_port on RunCommand: the call answers once your server listens, while it runs on.
  • Public ports (settings.ingress.public_ports, up to 20) answer anyone, a browser included.
  • Private ports answer requests with Pethost-Token: <token>, from CreateLink with port: for programs, curl and a page's fetch.
  • A visit wakes a paused sandbox in about 0.2 s, its server where it was.

Step 1: Start a server and wait for its port

Start the server with wait_for_port. The call answers as soon as something listens on that port, within wait_seconds, and the server runs on. A server listening on localhost is reached too.

Python
server = sandboxes.run_command(
    sandbox_id,
    command="python3 -m http.server 5173",
    wait_for_port=5173,
)
print(server.state.name, server.command_id)  # RUNNING zldikyia4nbt
TypeScript
const server = await sandboxes.runCommand({
  sandboxId,
  command: "python3 -m http.server 5173",
  waitForPort: 5173,
});
console.log(server.state, server.commandId); // RUNNING
Go
server, err := client.RunCommand(ctx, &sandboxes.RunCommandRequest{
	SandboxID:   id,
	Command:     "python3 -m http.server 5173",
	WaitForPort: 5173,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(server.State, server.CommandID) // RUNNING
Rust
let server = sandboxes
    .run_command(RunCommandRequest {
        sandbox_id: id.clone(),
        command: "python3 -m http.server 5173".into(),
        wait_for_port: 5173,
        ..Default::default()
    })
    .await?;
println!("{:?} {}", server.state, server.command_id); // Running
CLI
$ pethost sandbox run api-dev -d --wait-for-port 5173 -- python3 -m http.server 5173
It runs on in the sandbox. Its output so far:  pethost api GetCommand '{"sandbox_id": "e9bprbw1hovj6sw5", "command_id": "gqiwdee8y868"}'
gqiwdee8y868

Step 2: Make the port public

A public port is in the sandbox's ingress settings. UpdateSandbox replaces the whole group, so send every port that should stay public; the answer has each one's url.

Python
from pethost.sandboxes import Ingress, PublicPort, SandboxSettings

sandbox = sandboxes.update_sandbox(
    sandbox_id,
    settings=SandboxSettings(ingress=Ingress(public_ports=[PublicPort(port=5173)])),
)
for port in sandbox.settings.ingress.public_ports:
    print(port.port, port.url)
# 5173 https://5173-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network
TypeScript
const updated = await sandboxes.updateSandbox({
  sandboxId,
  settings: { ingress: { publicPorts: [{ port: 5173 }] } },
});
for (const port of updated.settings?.ingress?.publicPorts ?? []) console.log(port.port, port.url);
Go
updated, err := client.UpdateSandbox(ctx, &sandboxes.UpdateSandboxRequest{SandboxID: id, Settings: &sandboxes.SandboxSettings{
	Ingress: &sandboxes.Ingress{PublicPorts: []sandboxes.PublicPort{{Port: 5173}}},
}})
if err != nil {
	log.Fatal(err)
}
for _, port := range updated.Settings.Ingress.PublicPorts {
	fmt.Println(port.Port, port.URL)
}
Rust
let ingress = Ingress { public_ports: vec![PublicPort { port: 5173, ..Default::default() }] };
let updated = sandboxes
    .update_sandbox(UpdateSandboxRequest {
        sandbox_id: id.clone(),
        settings: Some(SandboxSettings { ingress: Some(ingress), ..Default::default() }),
        ..Default::default()
    })
    .await?;
for port in updated.settings.and_then(|settings| settings.ingress).map(|ingress| ingress.public_ports).unwrap_or_default() {
    println!("{} {}", port.port, port.url);
}
CLI
$ pethost sandbox ports api-dev --open 5173
5173   https://5173-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network
MCP
UpdateSandbox {"sandbox_id": "…", "settings": {"ingress": {"public_ports": [{"port": 5173}]}}}

A port can be public from the start: pass the same ingress to CreateSandbox, or --public-port 5173 to pethost sandbox new.

Step 3: Or keep it private, behind a token

Any port that is not public answers only a request with the header Pethost-Token. CreateLink with port answers the port's address and a token for that port alone, which expires after an hour unless ttl_seconds says otherwise. Here a second server, started as in the first step, listens on 8080.

Python
link = sandboxes.create_link(sandbox_id, port=8080, ttl_seconds=3600)
print(link.url)
print(link.token)
# https://8080-e9bprbw1hovj6sw5.sbx1.sandboxes.pethost.network/
# sbl.eyJzIjoiZTlicHJidzFob3ZqNnN3NSIs…
TypeScript
const link = await sandboxes.createLink({ sandboxId, port: 8080, ttlSeconds: 3600 });
const answer = await fetch(link.url, { headers: { "Pethost-Token": link.token } });
console.log(answer.status);
Go
link, err := client.CreateLink(ctx, &sandboxes.CreateLinkRequest{
	SandboxID:  id,
	Target:     sandboxes.CreateLinkPort(8080),
	TTLSeconds: 3600,
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(link.URL)
fmt.Println(link.Token)
Rust
let link = sandboxes
    .create_link(CreateLinkRequest {
        sandbox_id: id.clone(),
        target: Some(CreateLinkRequestTarget::Port(8080)),
        ttl_seconds: 3600,
    })
    .await?;
println!("{}", link.url);
println!("{}", link.token);
CLI
$ curl -H "$(pethost sandbox url api-dev 8080 --token | tail -1)" "$(pethost sandbox url api-dev 8080)"
Port 8080 is private: a request sends its token, which --token prints. A browser opens a public port: pethost sandbox ports e9bprbw1hovj6sw5 --open 8080
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Directory listing for /</title>
…

The address of a port

A port's address is https://<port>-<sandbox id>.<server>, where the server is the one the sandbox runs on, such as https://5173-k7f3q2xy0a1b2c3d.sbx1.sandboxes.pethost.network. Take it from the answer (PublicPort.url, Link.url) rather than building it: a stopped sandbox that starts on another server changes its addresses with it.

Port 443 speaks HTTP/1.1 and HTTP/2, WebSockets included, with a certificate that is already there; port 80 answers with a redirect to HTTPS and nothing else. A sandbox's ports serve 896 requests at once. Every sandbox's address is under one domain, so the server takes the Domain off a cookie an answer sets: give an app's cookies the __Host- prefix, which keeps them to the app's own address.

Public or private

A public port answers anyone who has the address: that is what a browser's tab, an image or a WebSocket needs, since they cannot send a header. A private port is checked before anything else: a request without its token, or with another port's, is answered 401 before it wakes the sandbox. The server takes the header off, and the rest of the request reaches your program as it was sent, Authorization and Cookie included. It answers CORS for any origin, so a page of yours may fetch the port with a token it holds. The sandbox's connection token is root inside it and opens no port: a port's token is the one to give a page.

To open a private port in your own browser, forward it over SSH: ssh -L 8080:localhost:8080 <sandbox id>@<server> -p 2222, then open http://localhost:8080. SSH says how to sign in.

Previews that sleep

A request to a paused sandbox's port wakes it: the dev server is still running, with what it had in memory, and the first answer comes in about 0.2 s. So a preview of a branch or of an agent's work can pause minutes after its last visit and cost 30% of the running price until the next one:

  • Save the app as a template with its dependencies installed, so a new preview starts in about 0.22 s (templates).
  • Start it with its port public and its dev server running, started with wait_for_port.
  • Pause it early, with pause_after_idle_seconds 120, and turn the stop timer off (0), so the next visit always finds it paused rather than stopped.
  • Delete it when the branch is merged, or let delete_after_idle_seconds do it.

A preview of SMALL size visited 10 times a day costs about $4.26 a month this way: billing has the sum. A stopped sandbox's port answers 503, “stopped: resume it”, unless its lifecycle says wake_when_stopped (lifecycle).

When it does not work

  • 401 from a port: it is private and the request had no token, an expired one, or another port's. Make it public, or send Pethost-Token with a fresh token for that port.
  • An error page, or no answer: nothing listens on that port in the sandbox. Start the server with wait_for_port to know it listens, and check its output with GetCommand.
  • 503 “stopped: resume it”: the sandbox is stopped. ResumeSandbox starts it, its processes gone: start the server again, or keep previews paused rather than stopped.
  • wait_for_port answered after 45 s with no port: the server did not listen in time, or listens on another port. Read its output.
  • 403 “Blocked request. This host is not allowed.”: a Vite dev server checks the Host header, and the port's address is new to it. Give it server: { allowedHosts: true } in vite.config.js, or the address's host in that list.
  • A login does not stick: the app set a cookie for a wider domain, which the server takes off. Use a __Host- cookie.

Questions

How do I get a public URL for a port in a sandbox?

Add the port to settings.ingress.public_ports with UpdateSandbox, or run pethost sandbox ports <id> --open <port>. Its address is https://<port>-<sandbox id>.<server>.

Can I protect a port with a password?

A private port answers only requests with its token in the Pethost-Token header, which CreateLink makes. For a browser, forward it with ssh -L.

Do WebSockets work?

Yes, on public ports and on private ones from a client that sends the header, over HTTP/1.1 and HTTP/2.

Does a visit wake a paused sandbox?

Yes: in about 0.2 s, with its server still running. A stopped one wakes so only with wake_when_stopped.

How many ports can be public?

Up to 20 a sandbox. Any other port is reachable with a token.

Try Pethost Agent Sandboxes

A 7-day trial with $1 of usage and 4 vCPUs, with a card. Then a plan from $20 a month, which includes as much usage.

Start the trial