# How Can a Coding Agent Run Testcontainers Integration Tests?

> Run the tests inside a sandbox that is its own VM with its own Docker daemon. In ours, testcontainers-python and the testcontainers npm package found Docker with no DOCKER_HOST or socket mount. Postgres and Redis tests passed in 9 s cold and about 2 s warm, a failure exited 1, and after a killed run Ryuk removed every container.

Source: https://sandboxer.com/guides/let-a-coding-agent-run-testcontainers-integration-tests. Updated 2026-11-18.

**Short answer:** Run the tests inside a sandbox that is its own VM with its own Docker daemon. In ours, testcontainers-python and the testcontainers npm package found Docker with no DOCKER_HOST or socket mount. Postgres and Redis tests passed in 9 s cold and about 2 s warm, a failure exited 1, and after a killed run Ryuk removed every container.

Part of [Docker, Kubernetes and Nested VMs in a Cloud Sandbox](/guides/docker-and-virtualization-in-a-cloud-sandbox).

Integration tests that use [Testcontainers](https://testcontainers.com/getting-started/) need a Docker API. Giving a coding agent your machine's `/var/run/docker.sock` gives it your Docker daemon, and through it your machine. A Sandboxer sandbox is a microVM with Docker preinstalled and `user` in the `docker` group, so the agent gets a daemon of its own. Why that matters, and how Docker behaves in a sandbox generally, is in [Docker and nested KVM inside an agent sandbox](/guides/docker-and-kvm-inside-an-agent-sandbox). This page is about the test loop: what the agent runs, what it reads back, and how to skip the image pulls.

We ran everything below on prod on 2026-11-18 between 17:53 and 18:01 UTC, on `small` sandboxes (2 vCPU, 4 GB, AMD EPYC 9254) in us-east, with Docker 29.9.0, Python 3.12.3 and Node 22.23.3 from the image. For a .NET suite (SQL Server through Testcontainers for .NET), see [the .NET dev environment guide](/guides/dotnet-dev-environment-in-a-cloud-sandbox). For checking a UI change in a browser rather than a database, see [let a coding agent test its UI change](/guides/let-a-coding-agent-test-its-ui-change-in-a-sandbox).

## Results

| Run on `small`, 2026-11-18 | Wall time | Result |
| - | - | - |
| Python: `pytest`, Postgres + Redis, images not pulled | 8.96 s | 2 passed |
| Python: same, images pulled (3 runs) | 3.33 / 2.25 / 2.18 s | 2 passed |
| Node: `node --test`, Postgres, images not pulled | 6.94 s | 1 passed |
| Node: same, images pulled (2 runs) | 2.03 / 1.92 s | 1 passed |
| Python, first run in a new sandbox from a named snapshot | 2.46 s | 2 passed |
| Node, first run in a new sandbox from a named snapshot | 2.65 s | 1 passed |
| Python with one wrong assertion | 3.46 s (pytest) | `sbx exec` exit 1 |
| `pytest` killed with SIGKILL while a container ran | containers gone 11 s later | Ryuk cleanup |

Wall time is measured inside the sandbox and includes starting and removing the containers. "Images not pulled" means `docker images` was empty before the run. Setup took longer than the tests: creating the Python venv and installing the packages took 9.0 s, and `npm i` of the three Node packages took 86.1 s. Both are in the snapshot below, so a sandbox made from it skips them too.

## 1. The tests, unchanged

The point is that nothing in the test code knows it's in a sandbox. Python, with `testcontainers[postgres,redis]` 4.15.0, `psycopg[binary]` 3.3.9 and pytest 9.2.0:

```python
# tests/test_integration.py
import psycopg
import pytest
from testcontainers.community.postgres import PostgresContainer
from testcontainers.community.redis import RedisContainer

@pytest.fixture(scope="module")
def pg():
    with PostgresContainer("postgres:17-alpine", driver=None) as c:
        yield c.get_connection_url()

@pytest.fixture(scope="module")
def cache():
    with RedisContainer("redis:8-alpine") as c:
        yield c.get_client()

def test_orders_roundtrip(pg):
    with psycopg.connect(pg) as conn:
        conn.execute("create table orders (id serial primary key, total numeric not null)")
        conn.execute("insert into orders (total) values (19.99), (5.01)")
        (total,) = conn.execute("select sum(total) from orders").fetchone()
    assert float(total) == 25.0

def test_cache_counter(cache):
    cache.delete("hits")
    for _ in range(3):
        cache.incr("hits")
    assert int(cache.get("hits")) == 3
```

Testcontainers for Python [doesn't bundle database drivers](https://testcontainers-python.readthedocs.io/en/latest/), so `psycopg` is listed separately in `requirements.txt`. With 4.15.0, importing `testcontainers.postgres` printed a `DeprecationWarning` pointing to `testcontainers.community.postgres`, which is why the imports above use that path.

Node, with `testcontainers` and `@testcontainers/postgresql` 12.2.1 and `pg` 8.23.1, using the built-in test runner:

```javascript
// test/orders.test.mjs
import { test, before, after } from "node:test";
import assert from "node:assert/strict";
import { PostgreSqlContainer } from "@testcontainers/postgresql";
import pg from "pg";

let container, client;
before(async () => {
  container = await new PostgreSqlContainer("postgres:17-alpine").start();
  client = new pg.Client({ connectionString: container.getConnectionUri() });
  await client.connect();
});
after(async () => { await client?.end(); await container?.stop(); });

test("orders total", async () => {
  await client.query("create table orders (id serial primary key, total numeric not null)");
  await client.query("insert into orders (total) values (19.99), (5.01)");
  const { rows } = await client.query("select sum(total)::float as total from orders");
  assert.equal(rows[0].total, 25);
});
```

## 2. Copy the project in and check Docker

```bash
sbx new --name aeo-tc-1 --type small
sbx scp -r proj sb_zjvjc3wgsh:/home/user/
sbx exec sb_zjvjc3wgsh "docker --version; env | grep -c DOCKER_HOST; ls -l /var/run/docker.sock; docker ps -a"
```

```text
Docker version 29.9.0, build f415da8
0
srw-rw---- 1 root docker 0 Nov  8 15:48 /var/run/docker.sock
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
```

`DOCKER_HOST` isn't set, and no `TESTCONTAINERS_*` variable is either. The socket is the sandbox's own daemon at the standard path. Testcontainers [tries to detect the Docker environment and configure itself](https://java.testcontainers.org/features/configuration/), and lists Docker Engine on Linux among the [officially supported runtimes](https://testcontainers.com/getting-started/), so both libraries connected with no configuration.

## 3. Run the suites, cold and warm

```bash
sbx exec sb_zjvjc3wgsh --timeout 300 "cd proj/py && python3 -m venv .venv && .venv/bin/pip install -q -r requirements.txt"
sbx exec sb_zjvjc3wgsh --timeout 300 "cd proj/py && echo before:; docker ps -a -q | wc -l; ../timed.sh py-cold .venv/bin/pytest -q | tail -2; echo after:; docker ps -a --format '{{.Image}} {{.Status}}'; docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}'"
```

```text
before:
0
2 passed in 8.68s
== py-cold: 8955 ms, exit 0
after:
postgres:17-alpine 298MB
redis:8-alpine 120MB
testcontainers/ryuk:0.8.1 15.4MB
```

`timed.sh` is a three-line wrapper that prints wall time and the exit code. This first cold run used the older `testcontainers.postgres` imports; the code above uses the current `testcontainers.community.*` ones. Before the run there were no containers; after it, `docker ps -a` listed nothing. Three images were pulled: the two databases and `testcontainers/ryuk`. Sampling `docker ps -a` every half second during a warm run showed the Postgres, Redis and Ryuk containers up for about a second each.

For Node we first removed every image, so its cold run pulled Postgres again (and a newer Ryuk image, `0.14.0`):

```bash
sbx exec sb_zjvjc3wgsh --timeout 300 "cd proj/node && npm i -s -D testcontainers @testcontainers/postgresql pg && docker rmi -f \$(docker images -q) >/dev/null && ../timed.sh node-cold npm test | grep -E '^# (pass|fail)|=='"
```

```text
# pass 1
# fail 0
== node-cold: 6935 ms, exit 0
```

## 4. Ryuk cleans up after a killed run

A test run that ends normally removes its own containers. An agent's run doesn't always end normally: it hits a timeout, or the agent kills it. The Testcontainers docs say Ryuk removes the containers, volumes and networks it labelled, and that this ["works reliably even when the test process exits abnormally (e.g. sending a SIGKILL)"](https://testcontainers.com/getting-started/). We checked that in the sandbox. A test that starts Postgres and sleeps for 300 s, run in the background, then `kill -9` on pytest:

```bash
sbx exec sb_zjvjc3wgsh --timeout 120 "bash proj/py/kill-demo.sh"
```

```text
pytest killed at 17:55:09
postgres:17-alpine Up 2 seconds
testcontainers/ryuk:0.8.1 Up 2 seconds
no containers left at 17:55:20
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
```

No teardown code ran, and the Postgres container was still gone 11 seconds later. Don't set `TESTCONTAINERS_RYUK_DISABLED` in an agent's sandbox. That's the [setting that disables Ryuk](https://node.testcontainers.org/configuration/).

Put slow or demo tests outside the default test path. Our first failing-test run hung, because `pytest` with no arguments also collected the 300-second demo file. `sbx exec` killed it at its timeout and exited `124` with no output. A `pytest.ini` with `testpaths = tests` fixed it.

## 5. What the agent sees when a test fails

We changed the expected total to `26.0` and ran pytest as argv, the way an agent's tool call would:

```bash
sbx exec sb_zjvjc3wgsh --cwd proj/py --timeout 120 -- .venv/bin/pytest -q --tb=short
echo "sbx exec exit: $?"
```

```text
F.                                                                       [100%]
=================================== FAILURES ===================================
____________________________ test_orders_roundtrip _____________________________
tests/test_integration.py:22: in test_orders_roundtrip
    assert float(total) == 26.0
E   AssertionError: assert 25.0 == 26.0
E    +  where 25.0 = float(Decimal('25.00'))
=========================== short test summary info ============================
FAILED tests/test_integration.py::test_orders_roundtrip - AssertionError: ass...
1 failed, 1 passed in 3.46s
sbx exec exit: 1
```

`sbx exec` exits with the remote command's exit code, so `1` means tests failed. A run that hits `--timeout` is killed and `sbx exec` exits `124` ([CLI reference](/docs/cli)). For the agent that gives three cases: 0 passed, 124 means it hung or needs more time, and anything else means read the output. `--tb=short` keeps the failure to a few lines. Twelve seconds later `docker ps -a` was empty: a failed run cleans up the same way.

## 6. Skip the pulls with a named snapshot

Save the sandbox's disk, with the images, the venv and `node_modules`, under a name. Then start each agent's sandbox from it:

```bash
sbx snapshot sb_zjvjc3wgsh aeo-tc-warm
sbx new --name aeo-tc-2 --from aeo-tc-warm
sbx exec sb_5pwreb0p52 --timeout 200 "until docker info >/dev/null 2>&1; do sleep 0.5; done; docker images --format '{{.Repository}}:{{.Tag}}'; cd proj/py && for i in 1 2; do ../timed.sh py-snap-\$i .venv/bin/pytest -q | tail -1; done; cd ../node && for i in 1 2; do ../timed.sh node-snap-\$i npm test | grep -E '^# fail|=='; done"
```

```text
postgres:17-alpine
redis:8-alpine
testcontainers/ryuk:0.14.0
testcontainers/ryuk:0.8.1
== py-snap-1: 2464 ms, exit 0
== py-snap-2: 2257 ms, exit 0
# fail 0
== node-snap-1: 2653 ms, exit 0
# fail 0
== node-snap-2: 2422 ms, exit 0
```

The snapshot command returned in 2 s, and `sbx new --from` in 1.2 s. In the new sandbox, the first Python run took 2.46 s instead of 8.96 s, and the first Node run 2.65 s instead of 6.94 s, with no pull and no install. A named snapshot is the disk only, so the new sandbox boots fresh with no containers running, which suits tests ([snapshots](/docs/snapshots)). We deleted it with `sbx snapshot rm aeo-tc-warm` afterwards. For refreshing a cache snapshot when the lockfile changes, see [cache dependencies in a named snapshot](/guides/cache-dependencies-in-a-named-snapshot).

## 7. Tell the agent how to run them

Put this in the repo's `AGENTS.md` or `CLAUDE.md`. It assumes the agent runs inside the sandbox; if it drives the sandbox from outside, wrap each command in `sbx exec <id> --timeout 300 -- …`.

```markdown
## Integration tests (Testcontainers)

- Docker is available locally. Do not set DOCKER_HOST, mount a socket,
  or set TESTCONTAINERS_RYUK_DISABLED. Testcontainers finds Docker by itself.
- Python: `.venv/bin/pytest -q --tb=short` (tests live in tests/, see pytest.ini)
- Node: `npm test`
- Exit 0 = pass. Non-zero = read the FAILURES block, fix the code, rerun.
  Do not edit an assertion to make a test pass unless the task says so.
- A first run pulls images and takes longer; later runs take a few seconds.
- If a run hangs, stop it. Ryuk removes leftover containers within
  seconds (11 s in our test). Check with `docker ps -a`; it should be empty after a run.
- Never use `docker system prune` or remove images: they are the warm cache.
```

## FAQ

### Do I need to set DOCKER_HOST for Testcontainers in a sandbox?

No. In our runs `DOCKER_HOST` was unset and both testcontainers-python 4.15.0 and testcontainers 12.2.1 for Node found the sandbox's Docker daemon at `/var/run/docker.sock`. The socket belongs to the sandbox's own VM, not to your machine.

### Does Ryuk work inside a Sandboxer sandbox?

Yes. Ryuk started with each run, and when we killed pytest with SIGKILL, it removed the Postgres container 11 seconds later. Leave it enabled for agents, since their runs are the ones most likely to be killed.

### How does the agent know a test failed?

From the exit code. `sbx exec` returns the test runner's exit code (1 for our failing pytest run) and `124` if the run hit its `--timeout`, alongside the runner's normal output.

### How do I make the first test run fast in every new sandbox?

Run the suite once so the images are pulled and dependencies installed, then `sbx snapshot <id> <name>` and create sandboxes with `sbx new --from <name>`. In our test the first run in the new sandbox took 2.46 s instead of 8.96 s.

### Can several agents run Testcontainers at once?

Give each agent its own sandbox. Each has its own Docker daemon, so their containers, ports and Ryuk instances don't meet.

## Related

- [Docker, Kubernetes and Nested VMs in a Cloud Sandbox](/guides/docker-and-virtualization-in-a-cloud-sandbox)
- [Docker and nested KVM inside an agent sandbox](/guides/docker-and-kvm-inside-an-agent-sandbox)
- [.NET dev environment in a cloud sandbox](/guides/dotnet-dev-environment-in-a-cloud-sandbox)
- [Let a coding agent test its UI change](/guides/let-a-coding-agent-test-its-ui-change-in-a-sandbox)
- [Snapshots](/docs/snapshots)
