### Install Docker Node SDK Source: https://github.com/docker/node-sdk/blob/main/README.md Install the SDK using npm. This is the first step before using the library in your Node.js project. ```bash npm install @docker/node-sdk ``` -------------------------------- ### Create and Start a Docker Container Source: https://context7.com/docker/node-sdk/llms.txt Creates a container from an image with full `ContainerCreateRequest` configuration and then starts it. Supports detailed configuration for environment variables, port bindings, restart policies, and labels. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const { Id, Warnings } = await docker.containerCreate( { Image: 'nginx:alpine', Env: ['NGINX_PORT=8080'], ExposedPorts: { '8080/tcp': {} }, HostConfig: { PortBindings: { '8080/tcp': [{ HostPort: '8080' }] }, RestartPolicy: { Name: 'unless-stopped' }, Memory: 128 * 1024 * 1024, // 128 MB }, Labels: { 'managed-by': 'node-sdk' }, }, { name: 'my-nginx' }, ); console.log('Created container:', Id?.slice(0, 12)); if (Warnings?.length) console.warn('Warnings:', Warnings); await docker.containerStart(Id!); await docker.close(); ``` -------------------------------- ### containerCreate — Create a Container Source: https://context7.com/docker/node-sdk/llms.txt Creates (but does not start) a container from an image with full `ContainerCreateRequest` configuration. ```APIDOC ## containerCreate ### Description Creates (but does not start) a container from an image with full `ContainerCreateRequest` configuration. ### Method POST ### Endpoint /containers/create ### Parameters #### Request Body - **createConfig** (object) - Required - Configuration object for creating the container. Includes `Image`, `Env`, `ExposedPorts`, `HostConfig`, `Labels`, etc. - **options** (object) - Optional - Options for container creation, such as `name`. ### Request Example ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const { Id, Warnings } = await docker.containerCreate( { Image: 'nginx:alpine', Env: ['NGINX_PORT=8080'], ExposedPorts: { '8080/tcp': {} }, HostConfig: { PortBindings: { '8080/tcp': [{ HostPort: '8080' }] }, RestartPolicy: { Name: 'unless-stopped' }, Memory: 128 * 1024 * 1024, // 128 MB }, Labels: { 'managed-by': 'node-sdk' }, }, { name: 'my-nginx' }, ); console.log('Created container:', Id?.slice(0, 12)); if (Warnings?.length) console.warn('Warnings:', Warnings); await docker.containerStart(Id!); // Example of starting the created container await docker.close(); ``` ### Response #### Success Response (201 Created) - **Id** (string) - The ID of the newly created container. - **Warnings** (array of strings) - Any warnings generated during container creation. #### Response Example ```json { "Id": "a1b2c3d4e5f67890abcdef1234567890", "Warnings": [] } ``` ``` -------------------------------- ### Run Commands Inside a Container with Output Streaming Source: https://context7.com/docker/node-sdk/llms.txt Creates an exec instance in a running container, starts it with optional output streaming, and inspects the result. Ensure the container is running before executing. ```typescript import { DockerClient, Logger } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); // Create exec instance const { Id: execId } = await docker.containerExec('my-nginx', { Cmd: ['nginx', '-t'], AttachStdout: true, AttachStderr: true, }); // Start and capture output const output: string[] = []; await docker.execStart( execId!, new Logger((l) => output.push(l)), new Logger((l) => output.push(l)), ); // Inspect exit code const inspection = await docker.execInspect(execId!); console.log('Exit code:', inspection.ExitCode); console.log('Output:', output.join('\n')); // Output: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok await docker.close(); ``` -------------------------------- ### Execute Commands in a Container Source: https://context7.com/docker/node-sdk/llms.txt Creates an exec instance in a running container, starts it with optional output streaming, and inspects the result. This allows for running commands like 'nginx -t' inside the container and capturing their output. ```APIDOC ## containerExec / execStart / execInspect — Run Commands Inside a Container Creates an exec instance in a running container, starts it with optional output streaming, and inspects the result. ### Method `docker.containerExec(containerId, options)` `docker.execStart(execId, stdoutLogger, stderrLogger)` `docker.execInspect(execId)` ### Parameters #### containerExec - **containerId** (string) - The ID or name of the container. - **options** (object) - Options for the exec command. - **Cmd** (string[]) - The command to run. - **AttachStdout** (boolean) - Whether to attach to stdout. - **AttachStderr** (boolean) - Whether to attach to stderr. #### execStart - **execId** (string) - The ID of the exec instance. - **stdoutLogger** (Logger) - A logger for stdout. - **stderrLogger** (Logger) - A logger for stderr. #### execInspect - **execId** (string) - The ID of the exec instance. ### Response #### containerExec Success Response - **Id** (string) - The ID of the created exec instance. #### execInspect Success Response - **ExitCode** (number) - The exit code of the command. ### Request Example (containerExec) ```typescript const { Id: execId } = await docker.containerExec('my-nginx', { Cmd: ['nginx', '-t'], AttachStdout: true, AttachStderr: true, }); ``` ### Request Example (execStart) ```typescript await docker.execStart( execId!, new Logger((l) => output.push(l)), new Logger((l) => output.push(l)), ); ``` ### Request Example (execInspect) ```typescript const inspection = await docker.execInspect(execId!); ``` ### Response Example (execInspect) ```json { "ExitCode": 0 } ``` ``` -------------------------------- ### Get Container Resource Usage Statistics Source: https://context7.com/docker/node-sdk/llms.txt Returns a snapshot of CPU, memory, block I/O, and network statistics for a container, useful for monitoring container performance. ```APIDOC ## containerStats — Resource Usage Statistics Returns a snapshot of CPU, memory, block I/O, and network statistics for a container. ### Method `docker.containerStats(containerId, options)` ### Parameters #### containerStats - **containerId** (string) - The ID or name of the container. - **options** (object) - Options for retrieving stats. - **oneShot** (boolean) - If true, returns a single stat reading and exits. If false, streams stats. ### Response #### Success Response - **cpu_stats** (object) - CPU statistics. - **cpu_usage** (object) - CPU usage details. - **total_usage** (number) - Total CPU time consumed. - **system_cpu_usage** (number) - System CPU usage. - **memory_stats** (object) - Memory statistics. - **usage** (number) - Current memory usage. - **limit** (number) - Memory limit. ### Request Example ```typescript const stats = await docker.containerStats('my-nginx', { oneShot: true }); ``` ### Response Example ```json { "cpu_stats": { "cpu_usage": { "total_usage": 1234567890 }, "system_cpu_usage": 9876543210 }, "memory_stats": { "usage": 100000000, "limit": 200000000 } } ``` ``` -------------------------------- ### Get Docker Engine Version with systemVersion Source: https://context7.com/docker/node-sdk/llms.txt Fetch the Docker Engine version, API version, Go version, and Git commit hash. This is useful for compatibility checks and understanding the Docker daemon's specific build. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const ver = await docker.systemVersion(); console.log('Engine:', ver.Version); console.log('API:', ver.ApiVersion); console.log('Go:', ver.GoVersion); await docker.close(); ``` -------------------------------- ### Get Container Filesystem Changes Source: https://context7.com/docker/node-sdk/llms.txt Returns a list of files and directories that have been added, modified, or deleted in the container's writable layer, providing a diff of the container's filesystem. ```APIDOC ## containerChanges — Filesystem Diff Returns a list of files/directories that have been added (`1`), modified (`0`), or deleted (`2`) in the container's writable layer. ### Method `docker.containerChanges(containerId)` ### Parameters #### containerChanges - **containerId** (string) - The ID or name of the container. ### Response #### Success Response - **Kind** (number) - The type of change: 0 for Modified, 1 for Added, 2 for Deleted. - **Path** (string) - The path of the changed file or directory. ### Request Example ```typescript const changes = await docker.containerChanges('my-nginx'); ``` ### Response Example ```json [ { "Kind": 1, "Path": "/new-file.txt" }, { "Kind": 0, "Path": "/existing-file.conf" }, { "Kind": 2, "Path": "/deleted-file.log" } ] ``` ``` -------------------------------- ### Get Container Filesystem Changes (Diff) Source: https://context7.com/docker/node-sdk/llms.txt Returns a list of files/directories that have been added (`1`), modified (`0`), or deleted (`2`) in the container's writable layer. The `Kind` property indicates the type of change. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const changes = await docker.containerChanges('my-nginx'); for (const change of changes) { const kind = ['Modified', 'Added', 'Deleted'][change.Kind ?? 0]; console.log(`[${kind}] ${change.Path}`); } await docker.close(); ``` -------------------------------- ### Get Container Resource Usage Statistics Source: https://context7.com/docker/node-sdk/llms.txt Returns a snapshot of CPU, memory, block I/O, and network statistics for a container. The `oneShot: true` option retrieves a single snapshot. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const stats = await docker.containerStats('my-nginx', { oneShot: true }); const cpu = stats.cpu_stats?.cpu_usage?.total_usage ?? 0; const prevCpu = stats.precpu_stats?.cpu_usage?.total_usage ?? 0; const sysCpu = stats.cpu_stats?.system_cpu_usage ?? 1; const cpuPct = ((cpu - prevCpu) / sysCpu) * 100; const memUsed = (stats.memory_stats?.usage ?? 0) - (stats.memory_stats?.stats?.['cache'] ?? 0); const memLimit = stats.memory_stats?.limit ?? 1; console.log(`CPU: ${cpuPct.toFixed(2)}% MEM: ${(memUsed / memLimit * 100).toFixed(1)}%`); await docker.close(); ``` -------------------------------- ### Get Docker Daemon Information with systemInfo Source: https://context7.com/docker/node-sdk/llms.txt Retrieve detailed information about the Docker daemon, including OS, kernel version, CPU, memory, running containers, and storage driver details. This provides insights into the Docker environment. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const info = await docker.systemInfo(); console.log('OS:', info.OperatingSystem); console.log('Containers running:', info.ContainersRunning); console.log('Images:', info.Images); console.log('Storage driver:', info.Driver); // info.MemTotal, info.NCPU, info.DockerRootDir, info.HttpProxy, etc. await docker.close(); ``` -------------------------------- ### Get Docker Disk Usage Statistics Source: https://context7.com/docker/node-sdk/llms.txt Returns disk-usage statistics for images, containers, volumes, and build cache. Accepts an optional array to restrict which object types are computed. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const usage = await docker.systemDataUsage(['image', 'container', 'volume']); console.log('Images:', usage.Images?.length); console.log('Containers:', usage.Containers?.length); console.log('Volumes:', usage.Volumes?.length); const totalImageSize = usage.Images?.reduce((acc, img) => acc + (img.Size ?? 0), 0) ?? 0; console.log('Total image bytes:', totalImageSize); await docker.close(); ``` -------------------------------- ### DockerClient Instantiation Source: https://context7.com/docker/node-sdk/llms.txt Demonstrates how to instantiate the DockerClient using different methods for connecting to a Docker daemon. ```APIDOC ## DockerClient Instantiation `DockerClient` is the main entry point. Three static factory methods cover every common Docker host configuration; the constructor itself accepts a raw `undici` `Agent` for advanced use. ```typescript import { DockerClient } from '@docker/node-sdk'; // 1. Auto-detect from ~/.docker/config.json (respects DOCKER_HOST env var) const docker = await DockerClient.fromDockerConfig(); // 2. Explicit host string: unix socket, TCP, TCP+TLS, SSH, or Windows npipe const unixClient = await DockerClient.fromDockerHost('unix:/var/run/docker.sock'); const tcpClient = await DockerClient.fromDockerHost('tcp://192.168.1.10:2375'); const tlsClient = await DockerClient.fromDockerHost('tcp://192.168.1.10:2376', '/path/to/certs'); const sshClient = await DockerClient.fromDockerHost('ssh://deploy@build-server:22/var/run/docker.sock'); const npipeClient = await DockerClient.fromDockerHost('npipe:////./pipe/docker_engine'); // Windows // 3. Named Docker context (reads ~/.docker/contexts/meta/) const ctxClient = await DockerClient.fromDockerContext('my-remote-context'); // Custom user-agent and extra headers const customClient = await DockerClient.fromDockerConfig('my-app/1.0', { 'X-Tenant': 'acme' }); // Always close when done to release the socket pool await docker.close(); ``` ``` -------------------------------- ### Initialize Docker Client and List Containers Source: https://github.com/docker/node-sdk/blob/main/README.md Initialize the Docker client from your Docker configuration and retrieve a list of all containers. Ensure your Docker environment is accessible. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const containers = await docker.containerList({ all: true }); console.dir(containers); ``` -------------------------------- ### Container Lifecycle Control Source: https://context7.com/docker/node-sdk/llms.txt Methods for controlling the lifecycle of a container, including starting, stopping, restarting, killing, pausing, and unpausing. ```APIDOC ## containerStart / containerStop / containerRestart / containerKill / containerPause / containerUnpause ### Description Lifecycle control methods for containers. All accept a container ID or name. `stop` and `restart` accept an optional timeout; `kill` accepts a signal name. ### Methods - **containerStart(containerId: string): Promise** - **containerStop(containerId: string, options?: { timeout?: number; signal?: string }): Promise** - **containerRestart(containerId: string, options?: { timeout?: number; signal?: string }): Promise** - **containerKill(containerId: string, options?: { signal?: string }): Promise** - **containerPause(containerId: string): Promise** - **containerUnpause(containerId: string): Promise** ### Parameters #### Path Parameters (for all methods) - **containerId** (string) - Required - The ID or name of the container. #### Options (for `containerStop`, `containerRestart`, `containerKill`) - **timeout** (number) - Optional - The time in seconds to wait before killing the container (for stop and restart). - **signal** (string) - Optional - The signal to send to the container (for kill, stop, and restart). ### Request Example ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const id = 'my-nginx'; await docker.containerStart(id); await docker.containerPause(id); await docker.containerUnpause(id); await docker.containerRestart(id, { timeout: 10 }); // wait 10 s before SIGKILL await docker.containerStop(id, { timeout: 5, signal: 'SIGTERM' }); await docker.containerKill(id, { signal: 'SIGKILL' }); await docker.close(); ``` ``` -------------------------------- ### Project Release Steps Source: https://github.com/docker/node-sdk/blob/main/RELEASE.md Follow these commands to ensure your working copy is up-to-date, bump the version, and push the changes to the main branch. The GitHub workflow will handle the rest. ```bash # ensure working copy is up to date $ git pull Up to date ``` ```bash # bump version $ npm version x.y.z vx.y.z ``` ```bash # push to git $ git push main vx.y.z ``` -------------------------------- ### Get Image Layer History Source: https://context7.com/docker/node-sdk/llms.txt Retrieves the ordered list of layers and their creation commands for a given image. Useful for debugging or understanding image composition. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const history = await docker.imageHistory('nginx:alpine'); for (const layer of history) { console.log(layer.Id?.slice(0, 12), layer.Size, 'bytes —', layer.CreatedBy?.slice(0, 80)); } await docker.close(); ``` -------------------------------- ### Instantiate DockerClient Source: https://context7.com/docker/node-sdk/llms.txt Create a DockerClient instance using static factory methods. Auto-detects configuration, uses explicit host strings (supporting Unix sockets, TCP, TLS, SSH, and Windows named pipes), or named Docker contexts. Remember to close the client when done. ```typescript import { DockerClient } from '@docker/node-sdk'; // 1. Auto-detect from ~/.docker/config.json (respects DOCKER_HOST env var) const docker = await DockerClient.fromDockerConfig(); // 2. Explicit host string: unix socket, TCP, TCP+TLS, SSH, or Windows npipe const unixClient = await DockerClient.fromDockerHost('unix:/var/run/docker.sock'); const tcpClient = await DockerClient.fromDockerHost('tcp://192.168.1.10:2375'); const tlsClient = await DockerClient.fromDockerHost('tcp://192.168.1.10:2376', '/path/to/certs'); const sshClient = await DockerClient.fromDockerHost('ssh://deploy@build-server:22/var/run/docker.sock'); const npipeClient = await DockerClient.fromDockerHost('npipe:////./pipe/docker_engine'); // Windows // 3. Named Docker context (reads ~/.docker/contexts/meta/) const ctxClient = await DockerClient.fromDockerContext('my-remote-context'); // Custom user-agent and extra headers const customClient = await DockerClient.fromDockerConfig('my-app/1.0', { 'X-Tenant': 'acme' }); // Always close when done to release the socket pool await docker.close(); ``` -------------------------------- ### Get File Metadata in Container Source: https://context7.com/docker/node-sdk/llms.txt Returns filesystem metadata (name, size, mode, mtime, linkTarget) for a path inside a container without transferring content. ```APIDOC ## containerArchiveInfo — File Metadata in Container Returns filesystem metadata (name, size, mode, mtime, linkTarget) for a path inside a container without transferring content. ### Method `docker.containerArchiveInfo(containerId, path)` ### Parameters #### containerArchiveInfo - **containerId** (string) - The ID or name of the container. - **path** (string) - The path inside the container to inspect. ### Response #### Success Response - **name** (string) - The name of the file or directory. - **size** (number) - The size of the file in bytes. - **mode** (number) - The file mode (permissions) as an octal number. - **mtime** (string) - The last modification time. - **linkTarget** (string) - The target path if it's a symbolic link. ### Request Example ```typescript const info = await docker.containerArchiveInfo('my-nginx', '/etc/nginx/nginx.conf'); ``` ### Response Example ```json { "name": "nginx.conf", "size": 1024, "mode": 420, "mtime": "2023-10-27T10:00:00Z", "linkTarget": null } ``` ``` -------------------------------- ### systemVersion Source: https://context7.com/docker/node-sdk/llms.txt Fetches the Docker Engine version, API version, Go version, and Git commit hash. ```APIDOC ## systemVersion — Engine Version Returns the Docker Engine version, API version, Go version, and Git commit hash. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const ver = await docker.systemVersion(); console.log('Engine:', ver.Version); console.log('API:', ver.ApiVersion); console.log('Go:', ver.GoVersion); await docker.close(); ``` ``` -------------------------------- ### systemPing Source: https://context7.com/docker/node-sdk/llms.txt Performs a health check by returning the Docker API version string. Useful as a connectivity probe. ```APIDOC ## systemPing — Health Check Returns the Docker API version string. Useful as a connectivity probe or to discover API capabilities before making substantive calls. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); try { const apiVersion = await docker.systemPing(); console.log('API version:', apiVersion); // e.g. "1.52" } catch (err) { console.error('Docker daemon unreachable:', err); } finally { await docker.close(); } ``` ``` -------------------------------- ### List Local Images with Docker Node SDK Source: https://context7.com/docker/node-sdk/llms.txt Returns a summary list of all local Docker images. Supports filtering by labels, references, and dangling state. The `all` option can be set to `true` to include intermediate images. ```typescript import { DockerClient, Filter } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const images = await docker.imageList({ all: false, digests: true, filters: new Filter().add('dangling', 'false'), }); for (const img of images) { console.log(img.RepoTags?.join(', '), '—', img.Size, 'bytes'); } await docker.close(); ``` -------------------------------- ### Get File Metadata from Container Source: https://context7.com/docker/node-sdk/llms.txt Returns filesystem metadata (name, size, mode, mtime, linkTarget) for a path inside a container without transferring content. Useful for checking file properties before transfer. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const info = await docker.containerArchiveInfo('my-nginx', '/etc/nginx/nginx.conf'); console.log('Name:', info.name); console.log('Size:', info.size); console.log('Mode:', info.mode?.toString(8)); // octal permissions console.log('Modified:', info.mtime); await docker.close(); ``` -------------------------------- ### Manage Docker Volumes with Node.js SDK Source: https://context7.com/docker/node-sdk/llms.txt Create, list, inspect, and delete Docker volumes. Ensure the Docker daemon is running and accessible. ```typescript import { DockerClient, Filter } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); // Create a named volume const vol = await docker.volumeCreate({ Name: 'app-data', Driver: 'local', Labels: { 'app': 'my-app', 'environment': 'prod' }, }); console.log('Volume:', vol.Name, 'at', vol.Mountpoint); // List volumes filtered by label const list = await docker.volumeList( new Filter().add('label', 'app=my-app'), ); console.log('Volumes:', list.Volumes?.map((v) => v.Name)); // Inspect const info = await docker.volumeInspect('app-data'); console.log('Driver:', info.Driver, 'Scope:', info.Scope); // Delete await docker.volumeDelete('app-data', { force: false }); await docker.close(); ``` -------------------------------- ### DockerClient.fromDockerHost TLS Certificate Loading Source: https://context7.com/docker/node-sdk/llms.txt Explains how to load TLS certificates for secure connections when using `DockerClient.fromDockerHost`. ```APIDOC ## DockerClient.fromDockerHost — TLS Certificate Loading `DockerClient.fromDockerHost` accepts an optional second argument that is either a directory path containing `ca.pem`, `cert.pem`, and `key.pem`, or a raw `SecureContextOptions` object. ```typescript import { DockerClient } from '@docker/node-sdk'; import { readFileSync } from 'node:fs'; // Option A: directory path — SDK loads ca.pem, cert.pem, key.pem automatically const client = await DockerClient.fromDockerHost( 'tcp://prod-host:2376', '/home/ci/.docker/certs', ); // Option B: inline SecureContextOptions const client2 = await DockerClient.fromDockerHost('tcp://prod-host:2376', { ca: readFileSync('/certs/ca.pem'), cert: readFileSync('/certs/cert.pem'), key: readFileSync('/certs/key.pem'), }); const version = await client.systemVersion(); console.log(version.Version); // e.g. "27.5.1" await client.close(); ``` ``` -------------------------------- ### systemInfo Source: https://context7.com/docker/node-sdk/llms.txt Retrieves detailed information about the Docker daemon, including OS, kernel version, CPU, memory, and storage driver. ```APIDOC ## systemInfo — Daemon Information Returns detailed information about the Docker daemon — kernel version, OS, CPUs, memory, running containers, storage driver, etc. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const info = await docker.systemInfo(); console.log('OS:', info.OperatingSystem); console.log('Containers running:', info.ContainersRunning); console.log('Images:', info.Images); console.log('Storage driver:', info.Driver); // info.MemTotal, info.NCPU, info.DockerRootDir, info.HttpProxy, etc. await docker.close(); ``` ``` -------------------------------- ### Volume Management Source: https://context7.com/docker/node-sdk/llms.txt Provides methods for creating, listing, inspecting, deleting, and pruning Docker volumes. ```APIDOC ## volumeCreate / volumeList / volumeInspect / volumeDelete Full volume lifecycle management. ### Description Methods to manage the lifecycle of Docker volumes, including creation, inspection, listing, and deletion. ### Method `docker.volumeCreate(options)` `docker.volumeList(filter)` `docker.volumeInspect(name)` `docker.volumeDelete(name, options)` ### Parameters #### volumeCreate - **options** (object) - Required - Options for volume creation. - **Name** (string) - Required - The name of the volume. - **Driver** (string) - Required - The volume driver to use. - **Labels** (object) - Optional - User-defined metadata for the volume. #### volumeList - **filter** (Filter) - Optional - A Filter object to filter the list of volumes. #### volumeInspect - **name** (string) - Required - The name or ID of the volume to inspect. #### volumeDelete - **name** (string) - Required - The name or ID of the volume to delete. - **options** (object) - Optional - Options for deletion. - **force** (boolean) - Optional - Force deletion of the volume. ### Response #### Success Response (volumeCreate) - **Name** (string) - The name of the created volume. - **Mountpoint** (string) - The path where the volume is mounted. #### Success Response (volumeList) - **Volumes** (array) - An array of volume objects. #### Success Response (volumeInspect) - **Driver** (string) - The volume driver used. - **Scope** (string) - The scope of the volume. #### Success Response (volumeDelete) - No content on successful deletion. ``` ```APIDOC ## volumePrune — Remove Unused Volumes Deletes volumes not referenced by any container. Returns deleted names and reclaimed bytes. ### Description This method removes all unused Docker volumes that are not currently attached to any containers. It returns a list of deleted volume names and the total space reclaimed. ### Method `docker.volumePrune(filter)` ### Parameters #### volumePrune - **filter** (Filter) - Optional - A Filter object to filter which volumes are considered for pruning. ### Response #### Success Response - **VolumesDeleted** (array) - An array of names of the volumes that were deleted. - **SpaceReclaimed** (number) - The total amount of space reclaimed in bytes. ``` -------------------------------- ### Build an Image with Docker Node SDK Source: https://context7.com/docker/node-sdk/llms.txt Builds an image from a TAR-archive build context. The output can be streamed using `.messages()` or the image ID can be obtained by awaiting `.wait()`. Requires a Dockerfile content. ```typescript import { DockerClient } from '@docker/node-sdk'; import { pack } from 'tar-stream'; import { Readable } from 'node:stream'; async function buildContext(dockerfile: string): Promise { const p = pack(); p.entry({ name: 'Dockerfile' }, dockerfile); p.finalize(); return Readable.toWeb(p) as ReadableStream; } const docker = await DockerClient.fromDockerConfig(); const ctx = await buildContext('FROM alpine\nRUN echo "built"\nCMD ["sh"]'); const build = docker.imageBuild(ctx, { tag: 'my-app:latest', version: '2' }); // Stream build output for await (const msg of build.messages()) { if (msg.stream) process.stdout.write(msg.stream); if (msg.errorDetail) throw new Error(msg.errorDetail.message); } // Or just await the image ID // const imageId = await build.wait(); await docker.close(); ``` -------------------------------- ### containerList — List Containers Source: https://context7.com/docker/node-sdk/llms.txt Returns a list of containers. By default only running containers are shown; pass `all: true` for all states. Supports `Filter` objects for label, status, ancestor, network, and other criteria. ```APIDOC ## containerList ### Description Returns a list of containers. By default only running containers are shown; pass `all: true` for all states. Supports `Filter` objects for label, status, ancestor, network, and other criteria. ### Method GET ### Endpoint /containers/json ### Parameters #### Query Parameters - **all** (boolean) - Optional - If true, show all containers (default: false). - **limit** (number) - Optional - Maximum number of containers to return. - **size** (boolean) - Optional - If true, return the total size of all images used by each container (default: false). - **filters** (Filter) - Optional - A `Filter` object to filter the list of containers based on various criteria like labels, status, etc. ### Request Example ```typescript import { DockerClient, Filter } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); // All containers with a specific label const containers = await docker.containerList({ all: true, filters: new Filter().add('label', 'com.example.service=api'), }); for (const c of containers) { console.log(c.Id?.slice(0, 12), c.Names, c.Status, c.Image); } await docker.close(); ``` ### Response #### Success Response (200) - **containers** (array of objects) - A list of container objects, each containing details like `Id`, `Names`, `Image`, `Status`, `State`, etc. #### Response Example ```json [ { "Id": "a1b2c3d4e5f6", "Names": ["/my-nginx"], "Image": "nginx:alpine", "Status": "running", "State": "running", ... } ] ``` ``` -------------------------------- ### Push an Image to a Registry with Docker Node SDK Source: https://context7.com/docker/node-sdk/llms.txt Pushes a locally tagged image to a registry. Requires image tagging and authentication credentials. Progress can be monitored via streamed messages. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); await docker.imageTag('my-app:latest', 'registry.example.com/myteam/my-app', 'v1.2.0'); const push = docker.imagePush('registry.example.com/myteam/my-app', { tag: 'v1.2.0', credentials: { username: 'ci-bot', password: process.env.REGISTRY_TOKEN! }, }); for await (const msg of push.messages()) { if (msg.status) console.log(msg.status); if (msg.errorDetail) throw new Error(msg.errorDetail.message); } await docker.close(); ``` -------------------------------- ### Load TLS Certificates for DockerClient Source: https://context7.com/docker/node-sdk/llms.txt Configure TLS connections for `DockerClient.fromDockerHost` by providing a directory path with certificate files or an inline `SecureContextOptions` object. This is crucial for secure communication with Docker hosts over TCP. ```typescript import { DockerClient } from '@docker/node-sdk'; import { readFileSync } from 'node:fs'; // Option A: directory path — SDK loads ca.pem, cert.pem, key.pem automatically const client = await DockerClient.fromDockerHost( 'tcp://prod-host:2376', '/home/ci/.docker/certs', ); // Option B: inline SecureContextOptions const client2 = await DockerClient.fromDockerHost('tcp://prod-host:2376', { ca: readFileSync('/certs/ca.pem'), cert: readFileSync('/certs/cert.pem'), key: readFileSync('/certs/key.pem'), }); const version = await client.systemVersion(); console.log(version.Version); // e.g. "27.5.1" await client.close(); ``` -------------------------------- ### containerInspect Source: https://context7.com/docker/node-sdk/llms.txt Returns full low-level information about a container including state, mounts, network settings, and resource limits. ```APIDOC ## containerInspect — Inspect a Container ### Description Returns full low-level information about a container including state, mounts, network settings, and resource limits. ### Method ```typescript await docker.containerInspect(containerId: string, options?: { size?: boolean }): Promise ``` ### Parameters #### Path Parameters - **containerId** (string) - Required - The ID or name of the container to inspect. #### Query Parameters - **size** (boolean) - Optional - If true, return the total file sizes. Defaults to false. ### Request Example ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const info = await docker.containerInspect('my-nginx', { size: true }); console.log('Running:', info.State?.Running); console.log('PID:', info.State?.Pid); console.log('IP:', info.NetworkSettings?.IPAddress); console.log('RW layer size:', info.SizeRw, 'bytes'); await docker.close(); ``` ### Response #### Success Response (200) - **ContainerInspectInfo** - An object containing detailed information about the container. - **State** (object) - The current state of the container. - **Running** (boolean) - Indicates if the container is running. - **Pid** (number) - The process ID of the container. - **NetworkSettings** (object) - Network settings for the container. - **IPAddress** (string) - The IP address of the container. - **SizeRw** (number) - The total size of the container's writable layer in bytes. ``` -------------------------------- ### imageInspect Source: https://context7.com/docker/node-sdk/llms.txt Returns low-level metadata for a local image: architecture, OS, layers, config, repo digests, and more. ```APIDOC ## imageInspect — Inspect an Image ### Description Returns low-level metadata for a local image: architecture, OS, layers, config, repo digests, and more. ### Method ```typescript imageInspect ``` ### Parameters #### Path Parameters - **imageId** (string) - Required - The ID or name of the image to inspect. ### Response #### Success Response - **Id** (string) - The ID of the image. - **Architecture** (string) - The architecture of the image. - **Os** (string) - The operating system of the image. - **Size** (number) - The size of the image in bytes. - **RootFS** (object) - Information about the image's root filesystem. - **Layers** (array) - List of image layers. ### Request Example ```typescript const image = await docker.imageInspect('nginx:alpine'); console.log('ID:', image.Id?.slice(7, 19)); console.log('Architecture:', image.Architecture); console.log('OS:', image.Os); console.log('Size:', image.Size, 'bytes'); console.log('Layers:', image.RootFS?.Layers?.length); ``` ``` -------------------------------- ### List Processes in Container Source: https://context7.com/docker/node-sdk/llms.txt Runs `ps` inside the container and returns the column headers and process rows, providing a snapshot of the running processes within the container. ```APIDOC ## containerTop — List Processes in Container Runs `ps` inside the container and returns the column headers and process rows. ### Method `docker.containerTop(containerId, options)` ### Parameters #### containerTop - **containerId** (string) - The ID or name of the container. - **options** (object) - Options for the `ps` command. - **psArgs** (string) - Arguments to pass to `ps` (e.g., 'aux'). ### Response #### Success Response - **Titles** (string[]) - The column headers for the process list. - **Processes** (string[][]) - An array of process rows, where each row is an array of strings representing process details. ### Request Example ```typescript const top = await docker.containerTop('my-nginx', { psArgs: 'aux' }); ``` ### Response Example ```json { "Titles": ["USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND"], "Processes": [ ["root", "1", "0.0", "0.1", "12345", "6789", "?", "Ss", "Jan01", "0:00", "nginx: master process nginx -g daemon off;"] ] } ``` ``` -------------------------------- ### Manage Docker Networks Source: https://context7.com/docker/node-sdk/llms.txt Provides full network management including creation, listing, inspection, and removal of Docker networks. Supports custom drivers and filters. ```typescript import { DockerClient, Filter } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); // Create a custom bridge network const { Id: netId } = await docker.networkCreate({ Name: 'my-app-net', Driver: 'bridge', Options: { 'com.docker.network.bridge.name': 'app-br0' }, Labels: { app: 'my-app' }, }); console.log('Created network:', netId?.slice(0, 12)); // List networks with a label filter const nets = await docker.networkList({ filters: new Filter().add('label', 'app=my-app'), }); console.log('Networks:', nets.map((n) => n.Name)); // Inspect const details = await docker.networkInspect(netId!, { verbose: true }); console.log('Subnet:', details.IPAM?.Config?.[0]?.Subnet); // Delete await docker.networkDelete(netId!); await docker.close(); ``` -------------------------------- ### Commit a Container to an Image with Docker Node SDK Source: https://context7.com/docker/node-sdk/llms.txt Creates a new Docker image from the current state of a specified container. Optional parameters allow setting repository, tag, commit message, author, and Dockerfile-style changes. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const { Id } = await docker.imageCommit('my-nginx', { repo: 'custom-nginx', tag: 'v1', comment: 'Added custom nginx config', author: 'CI Pipeline', changes: 'ENV NGINX_CUSTOM=1', }); console.log('New image ID:', Id); await docker.close(); ``` -------------------------------- ### Check Docker Daemon Connectivity with systemPing Source: https://context7.com/docker/node-sdk/llms.txt Use `systemPing` to perform a health check and retrieve the Docker API version. This is useful for verifying connectivity before executing other commands. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); try { const apiVersion = await docker.systemPing(); console.log('API version:', apiVersion); // e.g. "1.52" } catch (err) { console.error('Docker daemon unreachable:', err); } finally { await docker.close(); } ``` -------------------------------- ### Inspect Registry Image Metadata with Node.js SDK Source: https://context7.com/docker/node-sdk/llms.txt Fetch manifest digest and platform information for an image directly from the registry without downloading the image. Requires registry access. ```typescript import { DockerClient } from '@docker/node-sdk'; const docker = await DockerClient.fromDockerConfig(); const info = await docker.distributionInspect('nginx:alpine'); console.log('Digest:', info.Descriptor?.digest); console.log('Platforms:'); for (const p of info.Platforms ?? []) { console.log(' -', p.os, '/', p.architecture, p.variant ?? ''); } await docker.close(); ``` -------------------------------- ### Fetch and Stream Container Logs Source: https://context7.com/docker/node-sdk/llms.txt Streams stdout and stderr from a container. Supports live tailing with `follow`, timestamps, and limiting output with `tail`. Output is directed to provided `Writable` streams. ```typescript import { DockerClient } from '@docker/node-sdk'; import { Writable } from 'node:stream'; const docker = await DockerClient.fromDockerConfig(); const stdoutLines: string[] = []; const stdout = new Writable({ write(chunk, _enc, cb) { stdoutLines.push(chunk.toString()); cb(); }, }); const stderr = new Writable({ write(chunk, _enc, cb) { process.stderr.write(chunk); cb(); }, }); await docker.containerLogs('my-nginx', stdout, stderr, { stdout: true, stderr: true, timestamps: true, tail: '100', follow: false, }); console.log(stdoutLines.join('')); await docker.close(); ``` -------------------------------- ### imageBuild Source: https://context7.com/docker/node-sdk/llms.txt Builds an image from a TAR-archive build context. Returns a `JSONMessages` object with streaming build output or a `.wait()` that resolves to the image ID. ```APIDOC ## imageBuild — Build an Image ### Description Builds an image from a TAR-archive build context. Returns a `JSONMessages` object with streaming build output or a `.wait()` that resolves to the image ID. ### Method ```typescript imageBuild ``` ### Parameters #### Path Parameters - **context** (ReadableStream) - Required - The build context as a TAR archive stream. #### Query Parameters - **tag** (string) - Optional - The tag to apply to the built image. - **version** (string) - Optional - The build version. ### Response #### Success Response - **imageId** (string) - The ID of the built image (when using `.wait()`). - **messages** (JSONMessages) - Stream of build output (when using `.messages()`). ### Request Example ```typescript async function buildContext(dockerfile: string): Promise { const p = pack(); p.entry({ name: 'Dockerfile' }, dockerfile); p.finalize(); return Readable.toWeb(p) as ReadableStream; } const ctx = await buildContext('FROM alpine\nRUN echo "built"\nCMD ["sh"]'); const build = docker.imageBuild(ctx, { tag: 'my-app:latest', version: '2' }); // Stream build output for await (const msg of build.messages()) { if (msg.stream) process.stdout.write(msg.stream); if (msg.errorDetail) throw new Error(msg.errorDetail.message); } // Or just await the image ID // const imageId = await build.wait(); ``` ```