# jg-local-docker

> Checks for Node.js scripts that Docker is local before using it, plus Compose service and container reads with loopback-only ports.

- **Version:** `0.3.0`
- **Runtimes:** Node.js
- **Install:** `npm install jg-local-docker`
- **On npm:** [jg-local-docker](https://www.npmjs.com/package/jg-local-docker)
- **Source:** [packages/jg-local-docker](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-local-docker)
- **Recipes:** [jg-local-docker recipes](https://jg-packages.jesusgraterol.dev/packages/jg-local-docker/recipes/index.md)

## Usage

Resolve the endpoint once, check that it's on this machine, and pin every later command to it:

```ts
import { listComposeServices, resolveLocalDockerHost, runDocker } from 'jg-local-docker';

const host = await resolveLocalDockerHost(); // such as 'unix:///var/run/docker.sock'
await runDocker(['compose', 'up', '--detach', '--wait'], {
  host,
  cwd: '/srv/app',
  timeoutSeconds: 300,
});
const services = await listComposeServices({ cwd: '/srv/app', host });
```

`resolveLocalDockerHost` accepts only a Unix socket (`unix://`) or a Windows named pipe (`npipe://`): `DOCKER_HOST` when it's set, and the current context's endpoint, which must match it. A `tcp://` endpoint is refused even on 127.0.0.1, because a forwarded port or a tunnel can reach another machine, and so is `ssh://`. Either throws `DOCKER_ENDPOINT_NOT_LOCAL` before the script sends anything to the daemon. `runDocker` passes the endpoint as `--host` first, so a `docker context use` between the check and a later command can't send that command somewhere else.

Check that a Compose stack publishes its ports on loopback only:

```ts
import { findPublicPorts, listComposeServices } from 'jg-local-docker';

declare const host: string;

for (const { service, url, publishedPort } of findPublicPorts(
  await listComposeServices({ cwd: '/srv/app', host }),
)) {
  console.error(`${service} publishes port ${publishedPort} on ${url}`);
}
```

`findPublicPorts` flags a port published on any address but `127.0.0.1` or `::1`, such as both halves of a port on `0.0.0.0` and `::`, and ignores a port only exposed to other containers. `listComposeServices` runs `docker compose ps --format json`, stopped containers included unless `all` is `false`, and `parseComposePs` reads that output when you run the command yourself, as one JSON object per line or one array.

Read one container's state, labels, and published ports:

```ts
import { inspectContainer } from 'jg-local-docker';

declare const host: string;

const cache = await inspectContainer('app-cache-1', {
  host,
  labels: ['com.docker.compose.project'],
});
// { id, name: 'app-cache-1', isRunning: true, health: 'healthy',
//   labels: { 'com.docker.compose.project': 'app' },
//   ports: [{ containerPort: 6379, protocol: 'tcp', hostIp: '127.0.0.1', hostPort: 6380 }] }
```

`inspectContainer` uses a fixed template that never reads the container's environment, command, mounts, or logs, which can hold secrets. A label the container doesn't have reads as `null`, and a container without a healthcheck has a `null` health.

Start a container a script owns, such as a test database, and remove it afterwards:

```ts
import { randomUUID } from 'node:crypto';
import { removeContainer, startContainer } from 'jg-local-docker';

declare const host: string;

const name = `app-test-redis-${randomUUID()}`;
const labels = { 'app.test.nonce': randomUUID() };
const redis = await startContainer({
  host,
  name,
  labels,
  image: 'redis:8.6.2-alpine',
  ports: [6379],
});
// ... use 127.0.0.1 and redis.ports[0]?.hostPort
await removeContainer(name, { host, labels });
```

`startContainer` creates the container with its name, its labels, and each port published on a random port of `127.0.0.1`, starts it, and reads it back: it must be the container created, with the name and every label, and publish each port exactly once on `127.0.0.1` and nothing else, or it throws `DOCKER_CONTAINER_NOT_OWNED` or `DOCKER_PORTS_NOT_LOOPBACK`. `createArgs` adds `docker create` arguments, such as `['--memory', '256m']`, and `command` the arguments after the image. Any failure after the creation, an aborted `signal` included, removes the container before the error is thrown. `removeContainer` removes a container only when it has the exact name and every label given, so a random label, such as a nonce, proves it's yours: it stops it, removes it with its anonymous volumes, and confirms it's gone, resolving to `false` when there was none.

`startOwnedContainer` does the same through an owner process, which removes the container when `release` is called, when your process exits or crashes, and on SIGINT and SIGTERM, which Ctrl+C sends the whole process group:

```ts
import { startOwnedContainer } from 'jg-local-docker';

declare const host: string;

const { container, release } = await startOwnedContainer({
  host,
  name: 'app-test-redis',
  labels: { 'app.test.nonce': crypto.randomUUID() },
  image: 'redis:8.6.2-alpine',
  ports: [6379],
});
// ... the tests
await release(); // removes the container, and waits for the owner to exit
```

The owner creates the container itself, so it knows the container's ID from the first moment, and removes that container only. Use it in a test runner's global setup, which may exit at once on Ctrl+C, so no run leaves a container behind. `release` throws `DOCKER_OWNER_FAILED` when the owner couldn't confirm the removal.

Every command runs without a shell, within a 30-second timeout and a 64 KiB output limit unless you pass others, which reject with jg-process's `PROCESS_TIMED_OUT` and `PROCESS_OUTPUT_TOO_LARGE`. `runDocker` resolves with any exit code; the other helpers throw `DOCKER_COMMAND_FAILED` on a non-zero one.

### Errors

| Code                         | When                                                                                                                                                   |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `DOCKER_NOT_FOUND`           | `docker` isn't on the `PATH`                                                                                                                           |
| `DOCKER_ENDPOINT_NOT_LOCAL`  | `DOCKER_HOST` or the current context names an endpoint that isn't a Unix socket or a named pipe, or the two differ                                     |
| `DOCKER_COMMAND_FAILED`      | A helper's command exits with another code than 0                                                                                                      |
| `DOCKER_OUTPUT_INVALID`      | Docker's output isn't in the expected format                                                                                                           |
| `DOCKER_CONTAINER_NOT_FOUND` | The container `inspectContainer` reads doesn't exist                                                                                                   |
| `DOCKER_INVALID_ARGUMENT`    | An argument isn't valid, such as an empty endpoint, a working directory that doesn't exist, or a service name that's an option                         |
| `DOCKER_CONTAINER_NOT_OWNED` | The container `removeContainer` found, or `startContainer` started, doesn't have the name and every label given                                        |
| `DOCKER_PORTS_NOT_LOOPBACK`  | A container `startContainer` started doesn't publish each port exactly once on `127.0.0.1`, such as when `createArgs` publishes another, or it stopped |
| `DOCKER_OWNER_FAILED`        | `startOwnedContainer`'s owner process failed to start, or exited without confirming the container's removal                                            |

`DOCKER_ENDPOINT_NOT_LOCAL`'s data says where the endpoint came from, `DOCKER_HOST` or `context`, never the endpoint, which can name a user. `DOCKER_COMMAND_FAILED`'s data holds the subcommand and the exit code, never stderr, because Compose's diagnostics can quote the project's configuration. jg-process's `PROCESS_START_FAILED`, `PROCESS_TIMED_OUT`, `PROCESS_OUTPUT_TOO_LARGE`, and `PROCESS_TREE_SURVIVED` pass through, and an aborted `signal` rejects with its reason.

## <a id="api-reference"></a>jg-local-docker API reference

Every export of `jg-local-docker@0.3.0`, 25 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

- Functions: [`findPublicPorts`](#api-findPublicPorts), [`inspectContainer`](#api-inspectContainer), [`isLocalDockerEndpoint`](#api-isLocalDockerEndpoint), [`listComposeServices`](#api-listComposeServices), [`parseComposePs`](#api-parseComposePs), [`removeContainer`](#api-removeContainer), [`resolveLocalDockerHost`](#api-resolveLocalDockerHost), [`runDocker`](#api-runDocker), [`startContainer`](#api-startContainer), [`startOwnedContainer`](#api-startOwnedContainer)
- Constants: [`DEFAULT_DOCKER_MAX_OUTPUT_BYTES`](#api-DEFAULT_DOCKER_MAX_OUTPUT_BYTES), [`DEFAULT_DOCKER_TIMEOUT_SECONDS`](#api-DEFAULT_DOCKER_TIMEOUT_SECONDS), [`ERRORS`](#api-ERRORS)
- Types: [`IComposePublisher`](#api-IComposePublisher), [`IComposeService`](#api-IComposeService), [`IContainerInspection`](#api-IContainerInspection), [`IContainerPort`](#api-IContainerPort), [`IInspectContainerOptions`](#api-IInspectContainerOptions), [`IListComposeServicesOptions`](#api-IListComposeServicesOptions), [`IOwnedContainer`](#api-IOwnedContainer), [`IPublicPort`](#api-IPublicPort), [`IRemoveContainerOptions`](#api-IRemoveContainerOptions), [`IResolveLocalDockerHostOptions`](#api-IResolveLocalDockerHostOptions), [`IRunDockerOptions`](#api-IRunDockerOptions), [`IStartContainerOptions`](#api-IStartContainerOptions)

### <a id="api-functions"></a>Functions

#### <a id="api-findPublicPorts"></a>`findPublicPorts`

*Function*

Finds the ports services publish on an address other than 127.0.0.1 or ::1, which another machine may reach, such as `0.0.0.0` or `::`. A port that's only exposed to other containers isn't published, so it's left out.

```ts
findPublicPorts(services: readonly IComposeService[]): IPublicPort[]
```

**Parameters**

- `services` `readonly IComposeService[]`: The services, such as listComposeServices gives.

**Returns** `IPublicPort[]`: The public ports, in the services' order.

**Example**

```ts
import { findPublicPorts, listComposeServices } from 'jg-local-docker';

declare const host: string;

const services = await listComposeServices({ cwd: '/srv/app', host });
if (findPublicPorts(services).length > 0) {
  // bind the ports to 127.0.0.1 in compose.yaml
}
```

#### <a id="api-inspectContainer"></a>`inspectContainer`

*Function*

Reads a container's ID, name, state, health, the labels asked for, and its published ports, with `docker inspect` and a fixed template that never reads its environment, command, mounts, or logs.

```ts
inspectContainer(
  ref: string,
  options: IInspectContainerOptions,
): Promise<IContainerInspection>
```

**Parameters**

- `ref` `string`: The container's name or ID.
- `options` `IInspectContainerOptions`: The endpoint, the label keys, and the limits.

**Returns** `Promise<IContainerInspection>`: A promise that resolves to the inspection.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_CONTAINER_NOT_FOUND`: The container doesn't exist.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { inspectContainer, resolveLocalDockerHost } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
const redis = await inspectContainer('app-cache-1', { host, labels: ['com.docker.compose.project'] });
const isLoopbackOnly = redis.ports.every(({ hostIp }) => hostIp === '127.0.0.1');
```

#### <a id="api-isLocalDockerEndpoint"></a>`isLocalDockerEndpoint`

*Function*

Checks whether a Docker endpoint is on this machine: a Unix socket (`unix://`) or a Windows named pipe (`npipe://`). A `tcp://` or an `ssh://` endpoint isn't, even on 127.0.0.1, because a forwarded port or a tunnel can reach another machine.

```ts
isLocalDockerEndpoint(host: unknown): host is string
```

**Parameters**

- `host` `unknown`: The endpoint, such as DOCKER_HOST's value.

**Returns** `host is string`: Whether it's local.

**Example**

```ts
import { isLocalDockerEndpoint } from 'jg-local-docker';

isLocalDockerEndpoint('unix:///var/run/docker.sock'); // true
isLocalDockerEndpoint('npipe:////./pipe/docker_engine'); // true
isLocalDockerEndpoint('tcp://127.0.0.1:2375'); // false
```

#### <a id="api-listComposeServices"></a>`listComposeServices`

*Function*

Lists a Compose project's containers with `docker compose ps --format json`, at the endpoint `host` names, stopped ones included unless `all` is false.

```ts
listComposeServices(
  options: IListComposeServicesOptions,
): Promise<IComposeService[]>
```

**Parameters**

- `options` `IListComposeServicesOptions`: The project's directory, the endpoint, which services, and the limits.

**Returns** `Promise<IComposeService[]>`: A promise that resolves to the services, in Compose's order.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { listComposeServices, resolveLocalDockerHost } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
const services = await listComposeServices({ cwd: '/srv/app', host, services: ['db', 'cache'] });
const isReady = services.every(({ state, health }) => state === 'running' && health !== 'unhealthy');
```

#### <a id="api-parseComposePs"></a>`parseComposePs`

*Function*

Parses `docker compose ps --format json` output: one JSON object per line, as current Compose writes it, or a single JSON array, with LF or CRLF line ends. Empty output is no services. Entries keep Compose's order, duplicates included, so a caller can tell a service that runs twice.

```ts
parseComposePs(stdout: string): IComposeService[]
```

**Parameters**

- `stdout` `string`: The command's stdout.

**Returns** `IComposeService[]`: The services.

**Throws**

- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.

**Example**

```ts
import { parseComposePs } from 'jg-local-docker';

const [service] = parseComposePs(
  '{"ID":"3d94","Name":"app-db-1","Service":"db","Project":"app","State":"running","Health":"healthy","ExitCode":0,"Publishers":[{"URL":"127.0.0.1","TargetPort":5432,"PublishedPort":5432,"Protocol":"tcp"}]}\n',
);
service?.health; // 'healthy'
```

#### <a id="api-removeContainer"></a>`removeContainer`

*Function*

Removes a container only when it has the exact name and every label given, such as one startContainer started: it stops it, removes it by ID with its anonymous volumes, and confirms it's gone. A container with that name but other labels, or found by an ID that starts with the name, is refused, so a name another program reuses is never removed.

```ts
removeContainer(
  name: string,
  options: IRemoveContainerOptions,
): Promise<boolean>
```

**Parameters**

- `name` `string`: The container's name.
- `options` `IRemoveContainerOptions`: The endpoint, the labels, and the limits.

**Returns** `Promise<boolean>`: A promise that resolves to true when it removed the container, and false when there was none.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_CONTAINER_NOT_OWNED`: The container isn't the one its name and labels describe.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { removeContainer, resolveLocalDockerHost } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
await removeContainer('app-test-redis', { host, labels: { 'app.test.nonce': 'a0b1c2' } });
```

#### <a id="api-resolveLocalDockerHost"></a>`resolveLocalDockerHost`

*Function*

Resolves the Docker endpoint the docker command would use, and checks that it's on this machine: DOCKER_HOST, when it's set, and the current context's endpoint, which must match it. Pass the result as `host` to every later command, so a context switch can't redirect them.

```ts
resolveLocalDockerHost(
  options?: IResolveLocalDockerHostOptions,
): Promise<string>
```

**Parameters**

- `options?` `IResolveLocalDockerHostOptions`: The environment to read and run docker with, and the limits. Defaults to `{}`.

**Returns** `Promise<string>`: A promise that resolves to the endpoint, such as `unix:///var/run/docker.sock`.

**Throws**

- `DOCKER_ENDPOINT_NOT_LOCAL`: The Docker endpoint isn't on this machine.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { resolveLocalDockerHost, runDocker } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
await runDocker(['compose', 'up', '--detach', '--wait'], { host, cwd: '/srv/app', timeoutSeconds: 300 });
```

#### <a id="api-runDocker"></a>`runDocker`

*Function*

Runs a docker command without a shell, within a timeout and an output limit. With `host`, it passes `--host` first, so the command goes to that endpoint even when the current context changes after the endpoint was checked. It resolves with the exit code, whatever it is, and the output decoded as UTF-8; a timeout or too much output rejects as jg-process's runProcess does.

```ts
runDocker(
  args: readonly string[],
  options?: IRunDockerOptions,
): Promise<IProcessResult>
```

**Parameters**

- `args` `readonly string[]`: The command's arguments, such as `['ps', '--format', 'json']`.
- `options?` `IRunDockerOptions`: The endpoint, the working directory, the environment, and the limits. Defaults to `{}`.

**Returns** `Promise<IProcessResult>`: A promise that resolves with the exit code and the output.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { resolveLocalDockerHost, runDocker } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
const { exitCode, stdout } = await runDocker(['volume', 'ls', '--quiet'], { host });
```

#### <a id="api-startContainer"></a>`startContainer`

*Function*

Creates a container, starts it, and reads it back with inspectContainer: it must be the one created, with the name and every label asked for, and publish each port exactly once, on a random port of 127.0.0.1, and nothing else. Any failure after the creation, an abort included, removes the container by its ID before the error is thrown. Labels such as a random nonce are what removeContainer later checks, so the container can't be confused with another of the same name.

```ts
startContainer(options: IStartContainerOptions): Promise<IContainerInspection>
```

**Parameters**

- `options` `IStartContainerOptions`: The endpoint, the name, the labels, the image, the ports, the extra arguments, the command, and the limits.

**Returns** `Promise<IContainerInspection>`: A promise that resolves to the running container.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_CONTAINER_NOT_FOUND`: The container doesn't exist.
- `DOCKER_CONTAINER_NOT_OWNED`: The container isn't the one its name and labels describe.
- `DOCKER_PORTS_NOT_LOOPBACK`: The container's ports aren't each published once on 127.0.0.1.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { randomUUID } from 'node:crypto';
import { removeContainer, resolveLocalDockerHost, startContainer } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
const labels = { 'app.test.nonce': randomUUID() };
const redis = await startContainer({ host, name: 'app-test-redis', labels, image: 'redis:8.6.2-alpine', ports: [6379] });
const port = redis.ports[0]?.hostPort; // a random port on 127.0.0.1
await removeContainer('app-test-redis', { host, labels });
```

#### <a id="api-startOwnedContainer"></a>`startOwnedContainer`

*Function*

Starts a container as startContainer does, through an owner process that removes it when this process disconnects from it: when `release` is called, when this process exits or crashes, or when it's interrupted. The owner creates the container itself, so it knows its ID from the first moment, and it handles SIGINT and SIGTERM, which Ctrl+C sends the whole process group, by removing the container before it exits. Use it for a container that must not outlive a test run, such as in a test runner's global setup, which may exit at once on Ctrl+C.

```ts
startOwnedContainer(options: IStartContainerOptions): Promise<IOwnedContainer>
```

**Parameters**

- `options` `IStartContainerOptions`: The endpoint, the name, the labels, the image, the ports, the extra arguments, the command, and the limits, as startContainer takes them.

**Returns** `Promise<IOwnedContainer>`: A promise that resolves to the running container, and `release`, which removes it and waits for the owner to exit.

**Throws**

- `DOCKER_INVALID_ARGUMENT`: An argument isn't valid.
- `DOCKER_COMMAND_FAILED`: The docker command failed.
- `DOCKER_CONTAINER_NOT_FOUND`: The container doesn't exist.
- `DOCKER_CONTAINER_NOT_OWNED`: The container isn't the one its name and labels describe.
- `DOCKER_PORTS_NOT_LOOPBACK`: The container's ports aren't each published once on 127.0.0.1.
- `DOCKER_OUTPUT_INVALID`: Docker's output isn't in the expected format.
- `DOCKER_OWNER_FAILED`: The container's owner process failed.
- `DOCKER_NOT_FOUND`: Docker isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { randomUUID } from 'node:crypto';
import { resolveLocalDockerHost, startOwnedContainer } from 'jg-local-docker';

const host = await resolveLocalDockerHost();
const { container, release } = await startOwnedContainer({
  host,
  name: `app-test-redis-${randomUUID()}`,
  labels: { 'app.test.nonce': randomUUID() },
  image: 'redis:8.6.2-alpine',
  ports: [6379],
});
// ... the tests, against 127.0.0.1 and container.ports[0]?.hostPort
await release();
```

### <a id="api-constants"></a>Constants

#### <a id="api-DEFAULT_DOCKER_MAX_OUTPUT_BYTES"></a>`DEFAULT_DOCKER_MAX_OUTPUT_BYTES`

*Constant*

the bytes a docker command's output may take when the options don't say (64 KiB)

```ts
const DEFAULT_DOCKER_MAX_OUTPUT_BYTES: 65536
```

#### <a id="api-DEFAULT_DOCKER_TIMEOUT_SECONDS"></a>`DEFAULT_DOCKER_TIMEOUT_SECONDS`

*Constant*

the seconds a docker command may run when the options don't say

```ts
const DEFAULT_DOCKER_TIMEOUT_SECONDS: 30
```

#### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

the codes for every error thrown by the package

```ts
const ERRORS: { DOCKER_NOT_FOUND: "DOCKER_NOT_FOUND"; DOCKER_ENDPOINT_NOT_LOCAL: "DOCKER_ENDPOINT_NOT_LOCAL"; DOCKER_COMMAND_FAILED: "DOCKER_COMMAND_FAILED"; DOCKER_OUTPUT_INVALID: "DOCKER_OUTPUT_INVALID"; DOCKER_CONTAINER_NOT_FOUND: "DOCKER_CONTAINER_NOT_FOUND"; DOCKER_INVALID_ARGUMENT: "DOCKER_INVALID_ARGUMENT"; DOCKER_CONTAINER_NOT_OWNED: "DOCKER_CONTAINER_NOT_OWNED"; DOCKER_PORTS_NOT_LOOPBACK: "DOCKER_PORTS_NOT_LOOPBACK"; DOCKER_OWNER_FAILED: "DOCKER_OWNER_FAILED" }
```

### <a id="api-types"></a>Types

#### <a id="api-IComposePublisher"></a>`IComposePublisher`

*Type*

a port a Compose service's container publishes, from `docker compose ps`

```ts
type IComposePublisher = {
    url: string;
    targetPort: number;
    publishedPort: number;
    protocol: string;
};
```

**Members**

- `url: string` (property): the host address the port is published on, such as '127.0.0.1', or '' when it isn't
- `targetPort: number` (property): the port inside the container
- `publishedPort: number` (property): the port on the host, or 0 when the port is only exposed to other containers
- `protocol: string` (property): 'tcp', 'udp', or 'sctp'

#### <a id="api-IComposeService"></a>`IComposeService`

*Type*

a Compose service's container, from `docker compose ps --format json`

```ts
type IComposeService = {
    id: string;
    name: string;
    service: string;
    project: string;
    state: string;
    health: string;
    exitCode: number;
    publishers: IComposePublisher[];
};
```

**Members**

- `id: string` (property): the container's full ID
- `name: string` (property): the container's name, such as 'app-db-1'
- `service: string` (property): the service's name in the Compose file
- `project: string` (property): the Compose project's name
- `state: string` (property): the container's state, such as 'running', 'exited', or 'restarting'
- `health: string` (property): the healthcheck's status, such as 'healthy', or '' without a healthcheck
- `exitCode: number` (property): the exit code of a container that stopped
- `publishers: IComposePublisher[]` (property): the ports the container publishes or exposes

#### <a id="api-IContainerInspection"></a>`IContainerInspection`

*Type*

what inspectContainer gives

```ts
type IContainerInspection = {
    id: string;
    name: string;
    isRunning: boolean;
    health: string | null;
    labels: Record<string, string | null>;
    ports: IContainerPort[];
};
```

**Members**

- `id: string` (property): the container's full ID
- `name: string` (property): the container's name, without Docker's leading '/'
- `isRunning: boolean` (property): whether it's running
- `health: string | null` (property): the healthcheck's status, such as 'healthy' or 'starting', or null without a healthcheck
- `labels: Record<string, string | null>` (property): the value of each label asked for, or null when the container doesn't have it
- `ports: IContainerPort[]` (property): the ports published on the host; a port only exposed to other containers isn't one

#### <a id="api-IContainerPort"></a>`IContainerPort`

*Type*

a container port published on the host

```ts
type IContainerPort = {
    containerPort: number;
    protocol: string;
    hostIp: string;
    hostPort: number;
};
```

**Members**

- `containerPort: number` (property): the port inside the container
- `protocol: string` (property): 'tcp', 'udp', or 'sctp'
- `hostIp: string` (property): the host address it's published on, such as '127.0.0.1' or '0.0.0.0'
- `hostPort: number` (property): the port on the host

#### <a id="api-IInspectContainerOptions"></a>`IInspectContainerOptions`

*Type*

what inspectContainer takes

```ts
type IInspectContainerOptions = {
    host: string;
    labels?: readonly string[] | undefined;
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `host: string` (property): the Docker endpoint, such as the one resolveLocalDockerHost gives
- `labels: readonly string[]` (property): the label keys to read, such as 'com.docker.compose.project'
- `env: NodeJS.ProcessEnv` (property): the environment docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds the command may run. Defaults to 30
- `signal: AbortSignal` (property): stops the command when it aborts

#### <a id="api-IListComposeServicesOptions"></a>`IListComposeServicesOptions`

*Type*

what listComposeServices takes

```ts
type IListComposeServicesOptions = {
    cwd: string;
    host: string;
    projectName?: string | undefined;
    profiles?: readonly string[] | undefined;
    services?: readonly string[] | undefined;
    all?: boolean | undefined;
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `cwd: string` (property): the Compose project's directory, where its compose.yaml is
- `host: string` (property): the Docker endpoint, such as the one resolveLocalDockerHost gives
- `projectName: string` (property): the project's name, instead of the one Compose derives from the directory
- `profiles: readonly string[]` (property): the profiles to enable, for services that belong to one
- `services: readonly string[]` (property): the services to list. Defaults to every one
- `all: boolean` (property): whether stopped containers are listed too. Defaults to true
- `env: NodeJS.ProcessEnv` (property): the environment docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds the command may run. Defaults to 30
- `signal: AbortSignal` (property): stops the command when it aborts

#### <a id="api-IOwnedContainer"></a>`IOwnedContainer`

*Type*

what startOwnedContainer gives: the running container, and the function that removes it

```ts
type IOwnedContainer = {
    container: IContainerInspection;
    release: () => Promise<void>;
};
```

**Members**

- `container: IContainerInspection` (property): the container, as inspectContainer reads it once it's running
- `release: () => Promise<void>` (property): removes the container and waits for its owner process to exit

#### <a id="api-IPublicPort"></a>`IPublicPort`

*Type*

a port a service publishes on an address other than a loopback one

```ts
type IPublicPort = IComposePublisher & {
    service: string;
    name: string;
};
```

#### <a id="api-IRemoveContainerOptions"></a>`IRemoveContainerOptions`

*Type*

what removeContainer takes

```ts
type IRemoveContainerOptions = {
    host: string;
    labels: Readonly<Record<string, string>>;
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `host: string` (property): the Docker endpoint, such as the one resolveLocalDockerHost gives
- `labels: Readonly<Record<string, string>>` (property): the labels the container must have, every one with the same value; at least one
- `env: NodeJS.ProcessEnv` (property): the environment docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds each docker command may run. Defaults to 30
- `signal: AbortSignal` (property): stops the removal when it aborts

#### <a id="api-IResolveLocalDockerHostOptions"></a>`IResolveLocalDockerHostOptions`

*Type*

what resolveLocalDockerHost takes

```ts
type IResolveLocalDockerHostOptions = {
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `env: NodeJS.ProcessEnv` (property): the environment DOCKER_HOST is read from and docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds `docker context inspect` may run. Defaults to 30
- `signal: AbortSignal` (property): stops the command when it aborts

#### <a id="api-IRunDockerOptions"></a>`IRunDockerOptions`

*Type*

what runDocker takes

```ts
type IRunDockerOptions = {
    host?: string | undefined;
    cwd?: string | undefined;
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    maxOutputBytes?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `host: string` (property): the Docker endpoint every command goes to, passed as --host, such as the one resolveLocalDockerHost gives. Without it, Docker uses DOCKER_HOST or the current context
- `cwd: string` (property): the directory docker runs in, such as a Compose project's
- `env: NodeJS.ProcessEnv` (property): the environment docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds the command may run before it's stopped. Defaults to 30
- `maxOutputBytes: number` (property): the bytes stdout and stderr may hold together. Defaults to 64 KiB
- `signal: AbortSignal` (property): stops the command when it aborts

#### <a id="api-IStartContainerOptions"></a>`IStartContainerOptions`

*Type*

what startContainer and startOwnedContainer take

```ts
type IStartContainerOptions = {
    host: string;
    name: string;
    labels: Readonly<Record<string, string>>;
    image: string;
    ports: readonly number[];
    createArgs?: readonly string[] | undefined;
    command?: readonly string[] | undefined;
    env?: NodeJS.ProcessEnv | undefined;
    timeoutSeconds?: number | undefined;
    signal?: AbortSignal | undefined;
};
```

**Members**

- `host: string` (property): the Docker endpoint, such as the one resolveLocalDockerHost gives
- `name: string` (property): the container's name, which removeContainer finds it by
- `labels: Readonly<Record<string, string>>` (property): the labels that prove the container is this caller's, such as a random nonce; at least one
- `image: string` (property): the image, such as 'redis:8.6.2-alpine'
- `ports: readonly number[]` (property): the container's TCP ports to publish, each on a random port of 127.0.0.1
- `createArgs: readonly string[]` (property): more `docker create` arguments, before the image, such as ['--memory', '256m']
- `command: readonly string[]` (property): the command and its arguments, after the image
- `env: NodeJS.ProcessEnv` (property): the environment docker runs with. Defaults to process.env
- `timeoutSeconds: number` (property): the seconds each docker command may run. Defaults to 30
- `signal: AbortSignal` (property): stops the start when it aborts; a container already created is removed
