Skip to content
Guides · Sandboxes and isolation

nsjail vs bubblewrap vs a MicroVM for Untrusted Code

Updated November 23, 2026 .md

Short answer: Use bubblewrap or nsjail for a cheap per-run jail when you trust the kernel underneath. Both hid files and the network in our test, and nsjail also capped time, memory and processes. Neither has its own kernel, so a kernel bug escapes them. For untrusted or LLM-generated code, run the jail inside a microVM.

Part of Sandbox Isolation Compared: Containers, gVisor, Kata, MicroVMs, Wasm.

We ran one hostile-but-harmless Python script three ways in the same VM: under bubblewrap, under nsjail and directly. The script reads a secret file, connects out, forks 200 children, allocates 1 GB and spins the CPU for 12 seconds. This page covers the two jail tools. For the container-or-VM decision itself, see Container vs microVM. For a full wrapper built on systemd instead, see Run untrusted Python safely.

nsjail vs bubblewrap vs a microVM#

bubblewrap (bwrap) nsjail MicroVM
What isolates the code Linux namespaces; optional seccomp filter Namespaces, rlimits, cgroups and seccomp-bpf (Kafel) policies Hardware virtualization (KVM) and the VMM
Kernel the code talks to The host's The host's The guest's own
Read ~/secret.txt (our run) FileNotFoundError: not mounted FileNotFoundError: not mounted Read it
Connect to 1.1.1.1:443 Network is unreachable Network is unreachable Connected
Fork 200 children All 200 forked: no limit Stopped at 31 (cgroup_pids_max: 32) All 200 forked
Allocate 1024 MB All 1024 MB: no limit Stopped at 235 MB (rlimit_as: 256) All 1024 MB
Spin the CPU for 12 s Ran 12 s Killed at 5.0 s (time_limit: 5), exit 137 Ran 12 s
Startup overhead, mean of 10 +2.4 ms +10.8 ms (includes about 4 ms for sudo) A VM boot; start one VM and jail many runs inside it
Install on Ubuntu 24.04 apt-get install bubblewrap (0.9.0) Not in the Ubuntu archive; built from source in 8 s A VM per workload
Kernel bug in an allowed syscall Escapes Escapes Stays in the guest kernel

Last checked: 2026-11-23, on prod. Every run was in one default Sandboxer sandbox (4 vCPU, 8 GB, kernel 6.18.56-sandboxer) created with --no-env, with Python 3.12, bubblewrap 0.9.0 from apt and nsjail built from commit ec259a3.

The "MicroVM" column is the script run directly in that VM, as the VM's own user. That is what the code reaches with no jail: everything the VM has. The VM boundary protects the machine underneath, not the files and network inside the VM.

What the projects say they are#

  • bubblewrap "is a tool for constructing sandbox environments" and "is not a complete, ready-made sandbox with a specific security policy". Its README adds that "the level of protection between the sandboxed processes and the host system is entirely determined by the arguments passed to bubblewrap." It uses unprivileged user namespaces, so any user can run it, and sets PR_SET_NO_NEW_PRIVS to turn off setuid binaries. It warns to pass --new-session unless you filter TIOCSTI with seccomp (CVE-2017-5226), and that "everything mounted into the sandbox can potentially be used to escalate privileges." (bubblewrap README)
  • bubblewrap has no resource limits. Its manual lists namespace, mount and --seccomp FD options (a compiled cBPF program you supply), and no memory, process or time limits. Pair it with prlimit, timeout or a cgroup.
  • nsjail is a "Linux process isolation tool using namespaces, resource limits, and seccomp-bpf syscall filters." It covers UTS, mount, PID, IPC, network, user, cgroup and time namespaces, rlimits, cgroup v1 and v2 memory and PID limits, a wall-time limit, and Kafel seccomp policies, set by flags or a protobuf config file. Its README gives a build-from-source path for Debian and Ubuntu. (nsjail README, config.proto)

The shared kernel: what these tools have in common with containers#

Both tools are built from the same kernel features as a container: namespaces, plus cgroups and seccomp if you add them. The jailed process still makes its system calls into the kernel it runs on. Our script printed os.uname().release in every run, and all three said 6.18.56-sandboxer, the VM's kernel.

So a bug in that kernel, reachable through a syscall the jail allows, gets out of bubblewrap and nsjail the way it gets out of a container. A seccomp policy shrinks the set of reachable syscalls. It doesn't add a second kernel. A VM does: the guest has its own kernel behind KVM, and a guest-kernel bug lands in the guest. Why that boundary is smaller, and what gVisor does in between, is in Container vs microVM and gVisor vs Kata vs Firecracker.

The two layers do different jobs. A jail separates one run from the files, network and resources of the machine it's on. A VM separates that whole machine from yours. For code you didn't write, use both: one VM per user or task, and a fresh jail per run inside it.

The hostile script#

The same file ran in all three places. Each probe prints what happened instead of crashing, so you can see which limit hit:

import os, socket, time
def probe(f):
    try: return f()
    except Exception as e: return f"{type(e).__name__} ({getattr(e, "strerror", None) or e})"
print("kernel:", os.uname().release, flush=True)
print("read secret:", probe(lambda: open("/home/user/secret.txt").read().strip()), flush=True)
print("network:", probe(lambda: socket.create_connection(("1.1.1.1", 443), timeout=3) and "connected"), flush=True)
kids = []
for _ in range(200):
    try: pid = os.fork()
    except OSError as e: print("fork stopped:", e.strerror, end=" | ", flush=True); break
    if pid == 0: time.sleep(1); os._exit(0)
    kids.append(pid)
for k in kids: os.waitpid(k, 0)
print("forks:", len(kids), "of 200", flush=True)
held = []
try:
    for _ in range(1024): held.append(bytearray(1 << 20))
except MemoryError: pass
print("memory:", len(held), "MB of 1024", flush=True)
del held
t = time.time()
while time.time() - t < 12: pass
print("cpu loop: ran 12 s", flush=True)

It is bounded on purpose: 200 forks that exit after a second, 1 GB, 12 seconds. A real fork bomb or memory bomb doesn't stop, so only a limit outside the code ends it.

bubblewrap: a read-only /usr, no network#

This gives Python a read-only /usr, a fresh /proc, /dev and /tmp, the script, and nothing else. --unshare-all adds new user, IPC, PID, network, UTS and cgroup namespaces:

bwrap --ro-bind /usr /usr --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 \
  --ro-bind /opt/jail/t.py /t.py --proc /proc --dev /dev --tmpfs /tmp \
  --unshare-all --die-with-parent --new-session python3 /t.py
kernel: 6.18.56-sandboxer
read secret: FileNotFoundError (No such file or directory)
network: OSError (Network is unreachable)
forks: 200 of 200
memory: 1024 MB of 1024
cpu loop: ran 12 s

The home directory isn't mounted, so the secret doesn't exist in the jail. The network namespace has only a loopback device. The forks, the memory and the CPU loop all ran, because bubblewrap sets no limits.

nsjail: time, memory, process and network limits#

nsjail took the same mounts from a config file, plus limits. We ran it with sudo so it could create a cgroup for the run; the code inside runs as uid 99999:

mode: ONCE
time_limit: 5
rlimit_as: 256
use_cgroupv2: true
cgroup_mem_max: 268435456
cgroup_pids_max: 32
clone_newnet: true
uidmap { inside_id: "99999" outside_id: "99999" }
gidmap { inside_id: "99999" outside_id: "99999" }
mount { src: "/usr" dst: "/usr" is_bind: true }
mount { src: "/lib" dst: "/lib" is_bind: true }
mount { src: "/lib64" dst: "/lib64" is_bind: true }
mount { src: "/bin" dst: "/bin" is_bind: true }
mount { src: "/opt/jail/t.py" dst: "/t.py" is_bind: true }
mount { dst: "/tmp" fstype: "tmpfs" rw: true }
mount { dst: "/proc" fstype: "proc" }
sudo nsjail/nsjail --config jail.cfg --really_quiet -- /usr/bin/python3 /t.py; echo "exit $?"
kernel: 6.18.56-sandboxer
read secret: FileNotFoundError (No such file or directory)
network: OSError (Network is unreachable)
fork stopped: Resource temporarily unavailable | forks: 31 of 200
memory: 235 MB of 1024
exit 137

Without --really_quiet, nsjail logs why the run ended:

[I][2026-11-23T11:12:42+0000] pid=2178 run time >= time limit (5 >= 5) ([STANDALONE MODE]). Killing it
[I][2026-11-23T11:12:42+0000] pid=2178 ([STANDALONE MODE]) terminated with signal: SIGKILL (9), (PIDs left: 0)

The PID cgroup allowed 32 tasks: Python plus 31 children. The 256 MB address-space limit turned the allocation into a MemoryError at 235 MB, before the 256 MB cgroup memory cap was needed. The wall-time limit killed the CPU loop at 5 seconds, and no processes were left.

Two things went wrong on the first try, and they're common. nsjail couldn't bind the script from /home/user, because the jail's user can't traverse a 750 home directory (open(''/home/user/t.py'', O_PATH | O_CLOEXEC) for bind source: Permission denied). We moved it to /opt/jail. And Ubuntu 24.04 has no nsjail package (apt-cache policy nsjail printed nothing), so we built it with the README's steps.

Startup overhead#

Ten runs of python3 -c pass each, timed with date +%s%N, in the same default sandbox on 2026-11-23:

direct python3 -c pass: mean 7.1 ms, min 6.7, max 8.0
bwrap  python3 -c pass: mean 9.5 ms, min 9.0, max 10.3
nsjail python3 -c pass: mean 17.9 ms, min 13.6, max 23.1
sudo true (baseline):   mean 4.0 ms, min 3.7, max 4.6

bubblewrap added about 2.4 ms per run. nsjail with the config above added about 10.8 ms, of which about 4 ms is sudo. Both are small next to booting a VM, which is why the pattern that works is one VM and many jails, not one VM per run. If you do want a fresh VM per call, see A fresh sandbox per tool call.

Which should I use?#

  • Your own code or reviewed code, and you want it kept away from your files: bubblewrap. It's one apt-get install, runs without root, and adds about 2 ms.
  • Code that may loop, fork or eat memory, and you trust the kernel: nsjail. It brings time, memory and process limits in one config, or add timeout, prlimit and a cgroup to bubblewrap yourself.
  • Untrusted or LLM-generated code on a machine you care about: a microVM per user or task, with either jail inside it for each run. The jail keeps runs apart; the VM keeps a kernel bug away from your host.
  • Code that needs Docker, systemd or root: neither jail. Use the VM directly. A Sandboxer sandbox is a Cloud Hypervisor microVM with its own kernel, and sandboxes share no kernel with each other (Security). Plans start at $20/mo.

Copy-paste: run hostile Python under bubblewrap, nsjail and the bare VM#

Install the CLI with curl -fsSL https://sandboxer.com/install | sh and sign in with sbx login. Then paste this. It creates a default sandbox with none of your secrets, installs bubblewrap, builds nsjail, runs the script three ways and deletes the sandbox. It uses jq on your machine.

id=$(sbx new --name aeo-jail-2 --type default --no-env --ttl 1800 --json | jq -r 'select(.event=="ready") | .id')
sbx exec --timeout 600 "$id" 'set -e
sudo apt-get update -qq >/dev/null && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y -qq bubblewrap autoconf bison flex gcc g++ git libprotobuf-dev libnl-route-3-dev libtool make pkg-config protobuf-compiler >/dev/null 2>&1
git clone -q https://github.com/google/nsjail.git && make -s -C nsjail -j4 >/dev/null 2>&1
sudo mkdir -p /opt/jail && echo "TOKEN=demo-not-a-real-secret" > ~/secret.txt
sudo tee /opt/jail/t.py >/dev/null <<"EOF"
import os, socket, time
def probe(f):
    try: return f()
    except Exception as e: return f"{type(e).__name__} ({getattr(e, "strerror", None) or e})"
print("kernel:", os.uname().release, flush=True)
print("read secret:", probe(lambda: open("/home/user/secret.txt").read().strip()), flush=True)
print("network:", probe(lambda: socket.create_connection(("1.1.1.1", 443), timeout=3) and "connected"), flush=True)
kids = []
for _ in range(200):
    try: pid = os.fork()
    except OSError as e: print("fork stopped:", e.strerror, end=" | ", flush=True); break
    if pid == 0: time.sleep(1); os._exit(0)
    kids.append(pid)
for k in kids: os.waitpid(k, 0)
print("forks:", len(kids), "of 200", flush=True)
held = []
try:
    for _ in range(1024): held.append(bytearray(1 << 20))
except MemoryError: pass
print("memory:", len(held), "MB of 1024", flush=True)
del held
t = time.time()
while time.time() - t < 12: pass
print("cpu loop: ran 12 s", flush=True)
EOF
cat > jail.cfg <<"EOF"
mode: ONCE
time_limit: 5
rlimit_as: 256
use_cgroupv2: true
cgroup_mem_max: 268435456
cgroup_pids_max: 32
clone_newnet: true
uidmap { inside_id: "99999" outside_id: "99999" }
gidmap { inside_id: "99999" outside_id: "99999" }
mount { src: "/usr" dst: "/usr" is_bind: true }
mount { src: "/lib" dst: "/lib" is_bind: true }
mount { src: "/lib64" dst: "/lib64" is_bind: true }
mount { src: "/bin" dst: "/bin" is_bind: true }
mount { src: "/opt/jail/t.py" dst: "/t.py" is_bind: true }
mount { dst: "/tmp" fstype: "tmpfs" rw: true }
mount { dst: "/proc" fstype: "proc" }
EOF
set +e
echo "== directly in the VM"; python3 /opt/jail/t.py; echo "exit $?"
echo "== bubblewrap"
bwrap --ro-bind /usr /usr --symlink usr/bin /bin --symlink usr/lib /lib --symlink usr/lib64 /lib64 \
  --ro-bind /opt/jail/t.py /t.py --proc /proc --dev /dev --tmpfs /tmp \
  --unshare-all --die-with-parent --new-session python3 /t.py; echo "exit $?"
echo "== nsjail"; sudo nsjail/nsjail --config jail.cfg --really_quiet -- /usr/bin/python3 /t.py; echo "exit $?"'
sbx delete "$id" --yes
sbx info "$id"

Our run on 2026-11-23 on a default sandbox, from the second try described below (output piped, so sbx printed JSON; trimmed with …):

== directly in the VM
kernel: 6.18.56-sandboxer
read secret: TOKEN=demo-not-a-real-secret
network: connected
forks: 200 of 200
memory: 1024 MB of 1024
cpu loop: ran 12 s
exit 0
== bubblewrap
kernel: 6.18.56-sandboxer
read secret: FileNotFoundError (No such file or directory)
network: OSError (Network is unreachable)
forks: 200 of 200
memory: 1024 MB of 1024
cpu loop: ran 12 s
exit 0
== nsjail
kernel: 6.18.56-sandboxer
read secret: FileNotFoundError (No such file or directory)
network: OSError (Network is unreachable)
fork stopped: Resource temporarily unavailable | forks: 31 of 200
memory: 235 MB of 1024
exit 137
{"ok":true,"type":"deletion.operation","operation":{…,"status":"completed",…}}
{"event":"error","error":"Sandbox not found","code":"not_found","status":404,…}

The block didn't finish in one pass for us. On the first try the package mirror was slow and the sbx exec step hit its 600-second limit, printing nothing; the delete and the 404 still ran. We created a second sandbox to look at it (apt-get update alone took 116 s there), then ran the block's sbx exec step on it unchanged, followed by the delete and sbx info. That second sandbox had already run apt-get update once while we looked, so the step took 340 seconds, most of it apt-get, and printed the output above. If the step times out for you, run the sbx exec line again on the same sandbox before you delete it. The last line confirms the sandbox is gone.

FAQ#

Is bubblewrap a security boundary?#

Only as strong as the arguments you pass. Its README says it "is not a complete, ready-made sandbox" and that protection "is entirely determined by the arguments passed to bubblewrap". It also shares the host's kernel, like a container.

Does nsjail need root?#

nsjail can use unprivileged user namespaces, and its README's troubleshooting section covers enabling them. We ran it with sudo so it could create a cgroup v2 group for the memory and process limits.

Is a seccomp policy enough to make a jail as safe as a VM?#

No. Seccomp limits which syscalls reach the kernel, which shrinks what a bug can hit. The allowed syscalls still run in the host's kernel, so there is no second kernel between the code and your machine.

Can I run bubblewrap or nsjail inside a Sandboxer sandbox?#

Yes. Both ran in a default sandbox on 2026-11-23 with no extra setup: bubblewrap from apt, nsjail built from source. The sandbox's own kernel is the one they share, not the physical host's.

Which adds less startup time, bubblewrap or nsjail?#

In our 10-run test, bubblewrap added about 2.4 ms and nsjail about 10.8 ms, including about 4 ms for sudo. Both are small enough to start a fresh jail for every run.

More guides

Top AI sandbox platforms for code execution in 2026, ranked

For running AI-written code we rank Sandboxer, Freestyle and E2B first: each gives code its own VM with an API or SDK and can pause with memory. Pick Daytona for Windows or GPUs, Modal or Northflank for GPUs at scale, E2B or Northflank to run in your own cloud, and Vercel Sandbox if your app lives on Vercel.

Read the guide
Best sandboxes for running coding agents (Claude Code, Codex, Gemini CLI) in 2026, ranked

For coding agents we rank Sandboxer first: a full Ubuntu VM with Claude Code and Codex preinstalled, Docker, and stop-and-resume that keeps the agent's session in memory. Freestyle and Amp Orbs also keep memory across pauses. Pick E2B for prebuilt agent templates on open source, Docker Sandboxes for free local runs, and Codespaces if you live in GitHub.

Read the guide
Best Daytona sandbox alternatives in 2026, ranked

The best Daytona alternatives depend on why you're switching. For a full Linux microVM on every sandbox with memory-saving stop and Docker, we rank Sandboxer first. E2B suits open source and self-hosting, Modal massive short-job fleets, Northflank bring-your-own-cloud with GPUs, and Vercel Sandbox apps on Vercel.

Read the guide
Best E2B alternatives in 2026, ranked

If you're leaving E2B for longer sessions or a fuller machine, we rank Sandboxer first, then Freestyle: both give each sandbox a full Linux VM that keeps memory across pauses, with Docker and no short session cap. Pick Daytona for Windows or GPUs, Northflank for bring-your-own-cloud, and stay on E2B if you need open source.

Read the guide