Access web servers, databases, and other services running inside a sandbox from your host
Sometimes you need to reach a service running inside a sandbox — a web server, a database, or an API — from your host machine. SmolVM’s expose_local() method forwards a TCP port from the sandbox to localhost on your host so you can connect to it directly.
from smolvm import SmolVMwith SmolVM() as vm: # Start a web server in the guest vm.run("python3 -m http.server 8000 &") # Expose guest port 8000 to host localhost:8000 host_port = vm.expose_local(guest_port=8000, host_port=8000) print(f"Service available at http://127.0.0.1:{host_port}/") # Access the service from your host import requests response = requests.get(f"http://127.0.0.1:{host_port}/") print(response.text)
Omit host_port to let SmolVM choose an available port:
with SmolVM() as vm: vm.run("python3 -m http.server 8080 &") # SmolVM picks an available port automatically host_port = vm.expose_local(guest_port=8080) print(f"Guest port 8080 exposed on localhost:{host_port}")
Automatic port allocation is useful when the desired port might already be in use, or when running multiple VMs simultaneously.
def expose_local(self, guest_port: int, host_port: int | None = None) -> int: """Expose a guest TCP port on localhost only. Forwards 127.0.0.1:<host_port> on the host to <guest_ip>:<guest_port> inside the VM. Args: guest_port: Guest TCP port to expose. host_port: Host localhost port. If omitted, an available port is chosen. Returns: The host localhost port to connect to. """
Manually remove a port forward before VM shutdown:
with SmolVM() as vm: # Expose a port host_port = vm.expose_local(guest_port=8080, host_port=8080) print(f"Exposed on localhost:{host_port}") # Do work... # ... # Remove the forward vm.unexpose_local(host_port=8080, guest_port=8080) print("Port forward removed")
# If port 8080 is already in use, SmolVM tries a fallback porthost_port = vm.expose_local(guest_port=8080, host_port=8080)if host_port != 8080: print(f"Port 8080 unavailable, using {host_port} instead")
If expose_local() succeeds but the port is not reachable:
1
Verify the service is running
# Check if the service is listening in the guestresult = vm.run("netstat -tuln | grep 8080")print(result.output)
2
Check the service binds to the correct interface
Services must bind to 0.0.0.0 or the guest IP, NOT 127.0.0.1 only:
# Good - binds to all interfacesvm.run("python3 -m http.server 8000 --bind 0.0.0.0 &")# Bad - only accessible within the guestvm.run("python3 -m http.server 8000 --bind 127.0.0.1 &")
3
Test connectivity from inside the guest
result = vm.run("curl -v http://127.0.0.1:8000/")print(result.output)