> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Docker and Compose environments

> Run Docker and Docker Compose inside a VM sandbox: a whole stack with a database, a cache and your app, for an agent to work against, for integration tests, or as a dev environment that sleeps with every container up.

Real applications depend on other services: a Postgres database, a Redis cache, a message queue. An agent or an
integration test is only as useful as the environment it runs against, and **most projects already describe that
environment in a Docker Compose file** (`compose.yaml`).

A sandbox on the `vm` runtime can run Docker, so it can run that file exactly as it is. This opens up several uses:

* **An agent can build a feature against a real database**, instead of a fake one.
* **Integration tests can start the whole stack**, run, and throw everything away afterwards.
* **A development environment can stay up for days.** It **sleeps with every container still running**, so the
  next morning the stack is exactly where it was, data included.

## A stack with Postgres, from a compose file

**1. A VM sandbox with Docker running**

This sandbox starts from Docker's official image and runs the Docker daemon (the background service that manages
containers) as its main program. The last line waits until the daemon is ready:

```typescript title="TypeScript" run theme={null}
import { Sandbox } from "@fibre-dev/sdk";

const sbx = await Sandbox.create({
  image: "docker:27-dind",
  needs: ["docker"],
  entrypoint: ["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"],
  size: "medium",
  lifetime: 1800,
  labels: { docs: "compose" },
});
await sbx.run("until docker info > /dev/null 2>&1; do sleep 1; done", { timeout: 120 });
console.log(sbx.runtime); // vm
```

```python title="Python" run theme={null}
from fibre import Sandbox

sbx = Sandbox.create(
    image="docker:27-dind",
    needs=["docker"],
    entrypoint=["sh", "-c", "dind dockerd > /var/log/dockerd.log 2>&1"],
    size="medium",
    lifetime=1800,
    labels={"docs": "compose"},
)
sbx.run("until docker info > /dev/null 2>&1; do sleep 1; done", timeout=120)
print(sbx.runtime)  # vm
```

**2. The project's compose file**

In your own project, this file is already in the repository. For this example we write a small one: a Postgres
database, with a table and two rows created when it first starts.

```typescript title="TypeScript" run theme={null}
await sbx.files.write("/work/compose.yaml", `
services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: dev
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 2s
      retries: 30
`);
await sbx.files.write("/work/init.sql",
  "CREATE TABLE orders (id serial PRIMARY KEY, item text, qty int);\n" +
  "INSERT INTO orders (item, qty) VALUES ('widget', 3), ('gadget', 5);\n");
```

```python title="Python" run theme={null}
sbx.files.write("/work/compose.yaml", """
services:
  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_PASSWORD: dev
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
    healthcheck:
      test: ["CMD", "pg_isready", "-U", "postgres"]
      interval: 2s
      retries: 30
""")
sbx.files.write("/work/init.sql",
                "CREATE TABLE orders (id serial PRIMARY KEY, item text, qty int);\n"
                "INSERT INTO orders (item, qty) VALUES ('widget', 3), ('gadget', 5);\n")
```

**3. Bring it up**

Downloading the container images takes longer than an exec allows, so `sbx.run()` runs the command in the
background and waits for it. `--wait` makes Docker Compose wait until every service reports that it is healthy.

```typescript title="TypeScript" run theme={null}
const up = await sbx.run("cd /work && docker compose up -d --wait", { timeout: 600 });
console.log(up.exitCode); // 0: every service healthy
```

```python title="Python" run theme={null}
up = sbx.run("cd /work && docker compose up -d --wait", timeout=600)
print(up.exit_code)  # 0: every service healthy
```

**4. Use it**

Now the agent, your tests or you yourself can work with the real database:

```typescript title="TypeScript" run theme={null}
const query = await sbx.run(
  `cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT item, qty FROM orders ORDER BY id"`,
);
console.log(query.stdout); // widget|3 \n gadget|5

await sbx.run(`cd /work && docker compose exec -T db psql -U postgres -c "INSERT INTO orders (item, qty) VALUES ('doohickey', 7)"`);
```

```python title="Python" run theme={null}
query = sbx.run('cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT item, qty FROM orders ORDER BY id"')
print(query.stdout)  # widget|3 \n gadget|5

sbx.run("cd /work && docker compose exec -T db psql -U postgres -c \"INSERT INTO orders (item, qty) VALUES ('doohickey', 7)\"")
```

## It sleeps with the stack running

If you leave the sandbox alone, it goes to sleep after its idle timeout. **On the `vm` runtime, sleep keeps every
process**: the Docker daemon, the Postgres container, and the database's data both in memory and on disk. The next
call finds the stack still running, including the row added above.

```typescript title="TypeScript" norun reason="takes the idle timeout to fall asleep; the sleep page shows the same" theme={null}
// … hours later
const later = await Sandbox.get(sbx.id);
const rows = await later.run(`cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT count(*) FROM orders"`);
console.log(rows.stdout); // 3
```

```python title="Python" norun reason="takes the idle timeout to fall asleep; the sleep page shows the same" theme={null}
# … hours later
later = Sandbox.get(sbx.id)
rows = later.run('cd /work && docker compose exec -T db psql -U postgres -tAc "SELECT count(*) FROM orders"')
print(rows.stdout)  # 3
```

There is no need to run `docker compose up` again after a wake, to reload data, or to wait for health checks.

## Clean up

```typescript title="TypeScript" run theme={null}
await sbx.delete();
```

```python title="Python" run theme={null}
sbx.delete()
```

## Patterns

These are the most common ways to use a Docker sandbox:

| Use | How |
| - | - |
| **Agent with real services** | Install the agent in the same sandbox; it runs `docker compose` itself and tests against the stack |
| **Integration tests in CI** | Up, test, delete, from your [CI script](https://docs.fibre.dev/use-cases/ci.md); a `large` size for heavy stacks |
| **Per-developer dev environment** | One sandbox per developer, `idleTimeout` of an hour, kept until you delete it: it sleeps overnight with everything up |
| **Fast starts** | Bring the stack up once, then save the sandbox as a [snapshot](https://docs.fibre.dev/setup/snapshots.md): copies start with every container already running |

> [!NOTE]
>
> Docker needs the `vm` runtime, and `needs: ["docker"]` selects it for you. Images are downloaded from public
> registries, or from your own private registry once you store a [registry login](https://docs.fibre.dev/setup/registries.md).

## Related

> [card] [Runtimes](https://docs.fibre.dev/sandboxes/runtimes.md)
>
> What the `vm` runtime adds, and when you need it.

> [card] [Sleep and wake](https://docs.fibre.dev/sandboxes/sleep-and-wake.md)
>
> What sleep keeps on each runtime.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.