Skip to navigation

Docker Provider

View as MarkdownOpen in Claude

The docker provider runs each sandbox as one long-lived container on the local Docker daemon. It shells out to the docker CLI (docker run, docker exec, docker cp, docker rm), so it needs a running daemon but no OpenSandbox server, control plane, or Kubernetes. Use it for local development, CI, and single-machine setups where Docker is the available runtime.

Setup

Install Docker and make sure the docker binary is on PATH with a running daemon. The provider does not install or start Docker; constructing it raises RuntimeError if the binary is missing, and create() fails if the daemon is unreachable.

Images can be any reference the daemon can run, such as ubuntu:22.04, python:3.13.14-slim, or a registry reference. An Apptainer-style docker:// prefix is tolerated and stripped. GPU passthrough needs the NVIDIA Container Toolkit; CPU and memory limits need cgroups.

Provider Config

NeMo Gym ships a Docker provider config at nemo_gym/sandbox/providers/docker/configs/docker.yaml. It defines a top-level sandbox block that agents reference with sandbox_provider: sandbox.

sandbox:
default_metadata:
sandbox-api: docker-cli
docker:
create:
keepalive_shell: /bin/sh
keepalive_cmd: "while :; do sleep 2147483647; done"
start_timeout_s: 600
use_init: true
apply_resource_limits: true
# Isolation knobs -- opt in when running untrusted code (see Isolation and Security):
# network: none
# read_only: true
# cap_drop: ["ALL"]
# security_opt: ["no-new-privileges"]
# pids_limit: 512
exec:
default_timeout_s: 180
concurrency: 32
# exec_shell: /bin/bash # null auto-detects bash, then falls back to sh
probe:
command: printf docker-sandbox-ready
expected_stdout: docker-sandbox-ready
timeout_s: 30
deadline_s: 60
stable_count: 1

Run an agent with the provider config by passing it alongside the agent and model configs:

gym env start \
--config responses_api_agents/mini_swe_agent_2/configs/mini_swe_agent_2.yaml \
--config nemo_gym/sandbox/providers/docker/configs/docker.yaml \
--config responses_api_models/vllm_model/configs/vllm_model.yaml

The provider constructor accepts three optional config sections:

SectionPurpose
createKeep-alive command, docker run start timeout, --init zombie reaping, isolation flags (network, read-only root, dropped capabilities, security options, pids limit), and CPU/memory limit behavior.
execPer-command timeout, the shell used for <shell> -c <command> (auto-detected when unset), extra docker exec flags, and subprocess concurrency.
probePost-create command probe used to verify command execution before the sandbox is returned.

SandboxSpec Provider Options

Set Docker-specific create options under SandboxSpec.provider_options, or under sandbox_spec.provider_options in an agent config:

sandbox_spec:
provider_options:
volumes:
- /datasets/swebench:/datasets/swebench:ro
run_args: ["--shm-size", "1g"]
OptionPurpose
volumesA src:dst[:opts] bind-mount string or list of them, added as -v at docker run.
run_argsExtra raw flags appended to docker run for this sandbox.

Relevant SandboxSpec Fields

FieldDocker behavior
imageRequired. Any image the daemon can run. A docker:// prefix is stripped.
envPassed as --env KEY=VALUE at docker run and re-applied on each exec().
workdir-w at docker run (created if absent) and the default exec() working directory.
filesSeed files uploaded before the first command.
resourcesMapped to CPU, memory, and GPU flags (see Resource Mapping).
entrypointOverrides the keep-alive: the container runs this as its main process instead.
provider_optionsvolumes and run_args, applied per-sandbox.
ttl_sMax lifetime: the keep-alive sleeps for ttl_s and the container self-removes (--rm) on exit. Ignored when a custom entrypoint owns the container lifetime.

Resource Mapping

SandboxResources is translated into Docker CLI flags when create.apply_resource_limits is enabled:

SandboxResources fieldDocker flag
cpu--cpus <value>
memory_mib--memory <value>m, plus a matching --memory-swap so the limit is a hard cap rather than doubled through swap.
gpu--gpus <count> when nonzero (needs the NVIDIA Container Toolkit).
disk_gibNo direct flag; ignored.
gpu_typeNo direct flag; ignored.

Lifecycle

The provider runs one detached container per sandbox:

OperationDocker command
Createdocker run -d --name nemo-gym-<uuid> --label nemo-gym.sandbox=1 --init [flags] --entrypoint <shell> <image> -c <keepalive>
Execdocker exec [-w cwd] [--env ...] [--user ...] <name> <shell> -c <command>
PTY sessiondocker exec -i [-t] [-w cwd] [--env ...] --env NEMO_GYM_PTY_SESSION=<session id> [--user ...] <name> <shell> -c <launcher> <pid file> <fallback pid file> <program>, the client under a host pseudo-terminal (see Interactive Terminals)
Statusdocker inspect -f '{{.State.Status}}' <name>
Closedocker rm -f <name>

Containers are named nemo-gym-<uuid>, and the image ENTRYPOINT is overridden with a keep-alive command so images that define their own entrypoint (common for SWE benchmark images) stay up across exec() calls. State written by one command is visible to later commands in the same sandbox. --init inserts a minimal init process so the many short docker exec children are reaped instead of accumulating as zombies.

File Transfer

Uploads and downloads use docker cp in both directions, creating the target’s parent directory first on upload. Uploaded files are owned by root; read them as root or chown them for a non-root user. Download any files you need before stopping the sandbox — stopping force-removes the container.

Interactive Terminals

The provider implements SupportsSandboxPty, so await sandbox.pty.create(...), await sandbox.pty.exec(...) and the interactive sandbox shell (python -m nemo_gym.sandbox.shell) work on Docker as they do on OpenSandbox. A harness that drives a terminal session, such as a Terminus-2-style PTY harness, can build on them. The Terminus-2 sandboxed agent in this repository drives tmux over exec instead.

How a session runs

  • In PTY mode (the default), each session is one docker exec -i -t client running under a host pseudo-terminal of its own. The CLI sees a terminal, allocates one in the container and forwards bytes both ways; the session reads and writes the host terminal’s master side.
  • rows and cols size the host terminal before the client starts, and the CLI applies that size to the container’s terminal when the exec starts, so a program that reads its size at once sees the requested one. resize() changes the host terminal’s size and sends the client SIGWINCH, which the CLI turns into a resize of the container’s terminal.
  • cwd, env and user map to -w, --env and --user, as for exec().
  • pty=False runs the client on plain pipes: read() returns stdout and read_stderr() stderr.
  • With no command, create() starts a shell: bash when the image has it, else sh.
  • wait_exit() returns the program’s exit status as docker exec reports it.
  • Session clients are long-lived and are not counted against exec.concurrency. Stopping the sandbox releases its sessions before docker rm -f, and aclose() on the provider closes any still open.

The pid record

A one-line launcher records the program’s pid, then execs the program. send_signal() and close() reach the process through that pid.

  • The record goes to /tmp/.nemo-gym-pty-<session id>.pid, or to /dev/shm/.nemo-gym-pty-<session id>.pid when /tmp refuses the write (a container with read_only: true and no tmpfs on /tmp). /dev/shm is a writable tmpfs in every container that does not run with --ipc=none; under --ipc=host it is the host’s /dev/shm.
  • A session whose pid can be recorded in neither place could be neither signalled nor cleaned up, so the launcher does not start it. It prints nemo-gym: cannot record the pid of this PTY session in ... on stderr (the terminal in PTY mode) and exits 1, and the session ends at once with that message. create_pty() itself returns as soon as the client is spawned, without a round trip.
  • send_signal() and close() read the record the first time they need it, waiting up to two seconds for the launcher to write it: a call made right after create_pty() uses a second docker exec that races the session’s own to the daemon.

Signals and close

  • send_signal() takes "SIGINT", "SIGTERM", "SIGKILL", "SIGQUIT" or "SIGHUP" and runs kill as root through a second docker exec.
    • In PTY mode it signals the foreground process group of the session’s terminal (read from /proc/<pid>/stat), which is what a key press would reach: the program of a command session, or the job an interactive shell is running (the idle shell itself when there is none). A shell with job control runs each job in its own process group, so a signal to the shell’s group would never reach the running command.
    • In pipe mode, which has no terminal, it signals the process’s own group, then the process.
  • A docker client that goes away does not end the process it started, so close() of a live session ends it through one more exec: SIGHUP to the recorded process’s group, up to one second for a shell to relay the hangup to its jobs (under job control, an interactive shell’s foreground and background jobs sit in process groups of their own, which a signal to the shell’s group never reaches), then SIGKILL to every process still in the recorded process’s session, then to its group and the process itself (all a pipe-mode process that leads no session gets). Both pid paths are removed with it. close() of a session whose process already exited only removes them.
  • The in-container kill lines work in busybox sh (Alpine-based images) as well as dash and bash (kill -INT -<pgid>).

The session’s own user writes the pid file and can rewrite it, or replace it with a link to a file it does not own (in a world-writable /tmp a hard link keeps the linked inode’s owner). So neither the file’s content nor its owner is trusted as such:

  • It is read as the session’s own user, at most 32 bytes, under a timeout of its own: PID_READ_TIMEOUT_S (30 seconds), or exec.default_timeout_s when that is shorter. A pid that passes the checks below is kept; after a failed read, the next send_signal() or close() reads again. A path that is not a regular file (a FIFO, or a link to a device) is refused at once rather than opened, and the file is tested again on its opened descriptor, so swapping the path after the test cannot hand the read something that blocks.

  • The read runs as the session’s user because /proc/<pid>/environ is readable by the process’s own uid but not by a root without CAP_SYS_PTRACE, which Docker’s default capability set does not grant, so a root-side read would fail for every non-root session. The kill and the cleanup run as root and need no added capability.

  • The pid is followed only when it is a plain pid above 1 whose process:

    • carries the session’s marker, NEMO_GYM_PTY_SESSION=<session id>, in its environment (set by the session’s own docker exec --env, which a process can pass only to its own children);
    • has its parent outside the container (PPid 0 in the container’s pid namespace, true of a process the runtime injected and of nothing started inside it, the agent’s own children included);
    • and, in PTY mode, leads its session.

    Otherwise send_signal() raises SandboxPtyError and close() leaves the process to the container’s removal.

  • A rewritten or relinked record can therefore never aim the root-side kill at a process the session did not start. The session’s user can make its record useless, but cannot make send_signal() or close() wait on it past the two-second wait: a record that is not a regular file is refused at once, and any other unusable record (rewritten, relinked, emptied or removed) is refused by the end of that wait, so send_signal() raises and close() only removes the record.

Errors

When the daemon refuses the exec (the container is paused or gone, or the daemon is unreachable), the client exits without starting the program. Gym tells this from the client’s stderr, using the same lines that make exec() return error_type="sandbox", and ends the session with SandboxPtyError from wait_exit() and read() instead of reporting the client’s exit code as the program’s. So sandbox.pty.exec() raises where sandbox.exec() returns the runtime sentinel. In PTY mode the client’s own stderr is kept apart from the terminal output for this; in pipe mode it is the program’s stderr too, and is classified as exec() classifies its stderr. If the sandbox is stopped while create() opens a session, create() raises SandboxPtyError.

Limitations

  • No re-attach. Sessions live in the Gym process, not in the sandbox, so another process cannot re-attach by id (SupportsSandboxPtyAttach is not implemented).
  • detach=True runs attached. pty.exec(detach=True) stays attached, since there is no proxied connection to spare between polls.
  • Host pid namespace. send_signal() and close() rely on the container’s own pid namespace (PPid 0 marks the runtime’s execs), so a container that shares the host’s (--pid=host through extra_run_args) cannot be signalled or cleaned up through them.
  • Programs that change user. A session whose program changes its user or execs a setuid program (su, sudo -i) has an environment the session’s user can no longer read, so send_signal() raises and close() leaves the process to the container’s removal.
  • No writable /tmp or /dev/shm. A container with neither (read_only: true without a tmpfs on /tmp, and --ipc=none) cannot host a PTY session; it ends at once with the launcher’s message.

Isolation and Security

Docker containers share the host kernel. This is process and namespace isolation, not a virtual machine, and is not a hard boundary for hostile code. For adversarial or untrusted workloads, run Docker on a disposable VM or use a stronger runtime such as gVisor, Kata Containers, or a microVM.

  • Never run with --privileged and never mount the Docker socket into the sandbox; either grants host root.
  • Networking is on by default because most tasks need egress (pip, git). Set network: none to cut it entirely, or network: <name> to attach a locked-down internal network.
  • Harden with read_only: true, cap_drop: ["ALL"], security_opt: ["no-new-privileges"], and pids_limit: <n> as a fork-bomb guard. Enforce resources so one sandbox cannot starve the host. read_only: true leaves /tmp read-only too (add extra_run_args: ["--tmpfs", "/tmp"] for programs that need one); PTY sessions keep working, their pid record moves to /dev/shm (see Interactive Terminals).
  • Rootless Docker narrows the blast radius (container root is not host root) and is recommended for shared machines; docker cp ownership and some --user behaviors differ under it.
  • Every container is labeled nemo-gym.sandbox=1. Reap leaks from an unclean shutdown with docker rm -f $(docker ps -aq --filter label=nemo-gym.sandbox=1).

User and Runtime Notes

The neutral user argument to exec() maps onto --user:

user valueBehavior
NoneRun as the image’s default user.
"root" or 0Run as --user 0.
Other user or uidPassed through as --user <value>.

A command given as a list of strings is passed to docker exec as the program and its arguments, without <shell> -c; user, env and cwd apply as for shell text.

By default exec_shell is unset, so the provider auto-detects bash once the container is ready (conda and SWE-bench setup commands use source, which POSIX sh/dash lack) and falls back to sh. Pin exec_shell to /bin/sh or /bin/bash to skip the per-create probe.

Command failures return SandboxExecResult with the command’s exit code. A command timeout returns code 125 with error_type="timeout", and a docker runtime failure — daemon down or container gone, detected via stderr markers — returns code 125 with error_type="sandbox". A timed-out command’s in-container process is reaped when the sandbox is closed, since docker rm -f stops the whole process tree.

Task folders

When the harbor Environment Server runs task folders on Docker:

  • A task whose Dockerfile needs a build is built with docker into the local daemon, so no registry is needed. This holds while no build repository is set. When builds.repository or NEMO_GYM_BUILD_REPOSITORY names one, the image is built with builds.tool, else the first of buildah, podman or docker on PATH, and pushed there (see Harbor image builds).
  • Compose tasks do not start on Docker, which cannot network a group of sandboxes. A task with a Compose file in environment/, or any task when the server’s compose_overlay names Compose files, fails at seed with Could not set up sandbox for '<task>': Sandbox provider does not support networking between sandboxes. The failure is reported as retryable, so --resume runs these tasks again, and they fail the same way, until each has used its NEMO_GYM_MAX_ROLLOUT_ATTEMPTS attempts (3 by default). Leave them out with --exclude-tasks, or run them on OpenSandbox (see Multi-Container Tasks).
  • Gym holds a running image ENTRYPOINT in one docker exec. That exec ends at exec.default_timeout_s (180 seconds by default), but the entrypoint keeps running, untracked. If it then exits non-zero during the rollout, the sample is still scored, not masked with harbor:entrypoint_failed. The exit status is only logged and kept as entrypoint-exit.txt.