CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-dockerode

Docker Remote API module for Node.js providing programmatic interface to Docker containers, images, volumes, networks, and services.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

swarm.mddocs/

Docker Swarm Operations

Complete Docker Swarm management including services, nodes, secrets, configs, and tasks. Docker Swarm provides orchestration capabilities for multi-container applications across multiple Docker hosts.

Swarm Management

Swarm Initialization and Management

Core swarm cluster operations available on the Docker client.

/**
 * Initialize Docker swarm
 * @param opts - Swarm initialization options
 * @param callback - Optional callback
 * @returns Promise resolving to swarm initialization result
 */
docker.swarmInit(opts: SwarmInitOptions, callback?: Function): Promise<SwarmInitResult>;

/**
 * Join existing swarm
 * @param opts - Swarm join options
 * @param callback - Optional callback
 * @returns Promise resolving to join result
 */
docker.swarmJoin(opts: SwarmJoinOptions, callback?: Function): Promise<object>;

/**
 * Leave swarm
 * @param opts - Leave options
 * @param callback - Optional callback
 * @returns Promise resolving to leave result
 */
docker.swarmLeave(opts?: SwarmLeaveOptions, callback?: Function): Promise<object>;

/**
 * Update swarm configuration
 * @param opts - Swarm update options
 * @param callback - Optional callback
 * @returns Promise resolving to update result
 */
docker.swarmUpdate(opts: SwarmUpdateOptions, callback?: Function): Promise<object>;

/**
 * Get swarm details
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to swarm details
 */
docker.swarmInspect(opts?: object, callback?: Function): Promise<SwarmInspectInfo>;

interface SwarmInitOptions {
  /** Listen address */
  ListenAddr?: string;
  /** Advertise address */
  AdvertiseAddr?: string;
  /** Data path address */
  DataPathAddr?: string;
  /** Data path port */
  DataPathPort?: number;
  /** Force new cluster */
  ForceNewCluster?: boolean;
  /** Swarm specification */
  Spec?: SwarmSpec;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface SwarmJoinOptions {
  /** Listen address */
  ListenAddr?: string;
  /** Advertise address */
  AdvertiseAddr?: string;
  /** Data path address */
  DataPathAddr?: string;
  /** Remote managers */
  RemoteAddrs: string[];
  /** Join token */
  JoinToken: string;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface SwarmLeaveOptions {
  /** Force leave even if node is manager */
  force?: boolean;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface SwarmUpdateOptions {
  /** Object version for optimistic concurrency control */
  version: number;
  /** Rotate worker join token */
  rotateWorkerToken?: boolean;
  /** Rotate manager join token */
  rotateManagerToken?: boolean;
  /** Swarm specification */
  Spec?: SwarmSpec;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface SwarmInitResult {
  /** Node ID */
  NodeID: string;
  /** Warning messages */
  Warnings: string[];
}

interface SwarmSpec {
  /** Swarm name */
  Name?: string;
  /** Node labels */
  Labels?: { [key: string]: string };
  /** Orchestration configuration */
  Orchestration?: {
    TaskHistoryRetentionLimit?: number;
  };
  /** Raft configuration */
  Raft?: {
    SnapshotInterval?: number;
    KeepOldSnapshots?: number;
    LogEntriesForSlowFollowers?: number;
    ElectionTick?: number;
    HeartbeatTick?: number;
  };
  /** Dispatcher configuration */
  Dispatcher?: {
    HeartbeatPeriod?: number;
  };
  /** CA configuration */
  CAConfig?: {
    NodeCertExpiry?: number;
    ExternalCAs?: ExternalCA[];
    SigningCACert?: string;
    SigningCAKey?: string;
    ForceRotate?: number;
  };
  /** Encryption configuration */
  EncryptionConfig?: {
    AutoLockManagers?: boolean;
  };
  /** Task defaults */
  TaskDefaults?: {
    LogDriver?: {
      Name?: string;
      Options?: { [key: string]: string };
    };
  };
}

interface SwarmInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Spec: SwarmSpec;
  TLSInfo: TLSInfo;
  RootRotationInProgress: boolean;
  DataPathPort: number;
  DefaultAddrPool: string[];
  SubnetSize: number;
  JoinTokens: {
    Worker: string;
    Manager: string;
  };
}

Usage Examples:

// Initialize swarm
const swarmInit = await docker.swarmInit({
  ListenAddr: '0.0.0.0:2377',
  AdvertiseAddr: '192.168.1.100',
  Spec: {
    Name: 'my-swarm',
    Orchestration: {
      TaskHistoryRetentionLimit: 10
    }
  }
});

console.log(`Node ID: ${swarmInit.NodeID}`);

// Join swarm as worker
await docker.swarmJoin({
  ListenAddr: '0.0.0.0:2377',
  AdvertiseAddr: '192.168.1.101',
  RemoteAddrs: ['192.168.1.100:2377'],
  JoinToken: 'SWMTKN-1-...'
});

// Get swarm information
const swarmInfo = await docker.swarmInspect();
console.log(`Swarm ID: ${swarmInfo.ID}`);
console.log(`Worker token: ${swarmInfo.JoinTokens.Worker}`);

// Leave swarm
await docker.swarmLeave({ force: false });

Service Management

Service Instance

Service objects represent Docker Swarm services for application deployment.

/**
 * Service instance representing a Docker Swarm service
 */
class Service {
  /** Service ID */
  id: string;
  /** Docker modem instance for API communication */
  modem: any;
  
  constructor(modem: any, id: string);
}

Service Operations

Manage service lifecycle, scaling, and monitoring.

/**
 * Get service details and configuration
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to service details
 */
inspect(opts?: ServiceInspectOptions, callback?: Function): Promise<ServiceInspectInfo>;

/**
 * Remove service
 * @param opts - Remove options
 * @param callback - Optional callback
 * @returns Promise resolving to remove result
 */
remove(opts?: ServiceRemoveOptions, callback?: Function): Promise<object>;

/**
 * Update service configuration
 * @param auth - Registry authentication
 * @param opts - Update options
 * @param callback - Optional callback
 * @returns Promise resolving to update result
 */
update(auth?: object, opts?: ServiceUpdateOptions, callback?: Function): Promise<ServiceUpdateResponse>;

/**
 * Get service logs
 * @param opts - Log options
 * @param callback - Optional callback
 * @returns Promise resolving to log stream
 */
logs(opts?: ServiceLogsOptions, callback?: Function): Promise<Stream>;

interface ServiceInspectOptions {
  /** Insert default values */
  insertDefaults?: boolean;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface ServiceRemoveOptions {
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface ServiceUpdateOptions {
  /** Object version for optimistic concurrency control */
  version: number;
  /** Registry authentication */
  registryAuthFrom?: string;
  /** Rollback to previous version */
  rollback?: string;
  /** Service specification */
  Spec?: ServiceSpec;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface ServiceLogsOptions {
  /** Return stdout logs */
  stdout?: boolean;
  /** Return stderr logs */
  stderr?: boolean;
  /** Return timestamps */
  timestamps?: boolean;
  /** Follow log output */
  follow?: boolean;
  /** Show logs since timestamp */
  since?: string | number;
  /** Number of lines from end of logs */
  tail?: number | string;
  /** Show task IDs in logs */
  details?: boolean;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface ServiceInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Spec: ServiceSpec;
  PreviousSpec?: ServiceSpec;
  Endpoint?: {
    Spec?: EndpointSpec;
    Ports?: PortConfig[];
    VirtualIPs?: {
      NetworkID: string;
      Addr: string;
    }[];
  };
  UpdateStatus?: {
    State: 'updating' | 'paused' | 'completed' | 'rollback_started' | 'rollback_paused' | 'rollback_completed';
    StartedAt: string;
    CompletedAt: string;
    Message: string;
  };
  ServiceStatus?: {
    RunningTasks: number;
    DesiredTasks: number;
    CompletedTasks: number;
  };
  JobStatus?: {
    JobIteration: ObjectVersion;
    LastExecution: string;
  };
}

interface ServiceSpec {
  /** Service name */
  Name?: string;
  /** Service labels */
  Labels?: { [key: string]: string };
  /** Task template */
  TaskTemplate?: TaskSpec;
  /** Service mode */
  Mode?: {
    /** Replicated service */
    Replicated?: {
      Replicas?: number;
    };
    /** Global service */
    Global?: {};
    /** Replicated job */
    ReplicatedJob?: {
      MaxConcurrent?: number;
      TotalCompletions?: number;
    };
    /** Global job */
    GlobalJob?: {};
  };
  /** Update configuration */
  UpdateConfig?: UpdateConfig;
  /** Rollback configuration */
  RollbackConfig?: UpdateConfig;
  /** Networks */
  Networks?: NetworkAttachmentConfig[];
  /** Endpoint specification */
  EndpointSpec?: EndpointSpec;
}

Usage Examples:

// Get service details
const serviceInfo = await service.inspect();
console.log(`Service: ${serviceInfo.Spec.Name}`);
console.log(`Replicas: ${serviceInfo.Spec.Mode?.Replicated?.Replicas}`);
console.log(`Image: ${serviceInfo.Spec.TaskTemplate?.ContainerSpec?.Image}`);

// Update service (scale replicas)
await service.update(undefined, {
  version: serviceInfo.Version.Index,
  Spec: {
    ...serviceInfo.Spec,
    Mode: {
      Replicated: {
        Replicas: 5
      }
    }
  }
});

// Get service logs
const logStream = await service.logs({
  stdout: true,
  stderr: true,
  follow: true,
  tail: 100
});

logStream.on('data', chunk => {
  console.log(chunk.toString());
});

// Remove service
await service.remove();

Service Creation and Management (Docker Client)

Service creation and listing operations available on the Docker client.

/**
 * Create a new service (available on Docker client)
 * @param auth - Registry authentication
 * @param opts - Service creation options
 * @param callback - Optional callback
 * @returns Promise resolving to Service instance
 */
docker.createService(auth?: object, opts?: ServiceCreateOptions, callback?: Function): Promise<Service>;

/**
 * List services with filtering options (available on Docker client)
 * @param opts - Filtering and query options
 * @param callback - Optional callback
 * @returns Promise resolving to service list
 */
docker.listServices(opts?: ListServicesOptions, callback?: Function): Promise<ServiceInfo[]>;

interface ServiceCreateOptions {
  /** Service specification */
  Spec: ServiceSpec;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface ListServicesOptions {
  /** Service filters */
  filters?: {
    /** Filter by ID */
    id?: string[];
    /** Filter by label */
    label?: string[];
    /** Filter by mode */
    mode?: string[];
    /** Filter by name */
    name?: string[];
  };
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

Usage Examples:

// Create replicated service
const service = await docker.createService(undefined, {
  Spec: {
    Name: 'web-service',
    Labels: {
      'com.example.app': 'web'
    },
    TaskTemplate: {
      ContainerSpec: {
        Image: 'nginx:latest',
        Env: [
          'NODE_ENV=production'
        ]
      },
      Resources: {
        Limits: {
          MemoryBytes: 128 * 1024 * 1024, // 128MB
          NanoCPUs: 0.1 * 1000000000 // 0.1 CPU
        }
      },
      RestartPolicy: {
        Condition: 'on-failure',
        MaxAttempts: 3
      }
    },
    Mode: {
      Replicated: {
        Replicas: 3
      }
    },
    EndpointSpec: {
      Ports: [{
        Protocol: 'tcp',
        TargetPort: 80,
        PublishedPort: 8080,
        PublishMode: 'ingress'
      }]
    }
  }
});

// Create global service
const globalService = await docker.createService(undefined, {
  Spec: {
    Name: 'monitoring-agent',
    TaskTemplate: {
      ContainerSpec: {
        Image: 'monitoring:latest',
        Mounts: [{
          Type: 'bind',
          Source: '/var/run/docker.sock',
          Target: '/var/run/docker.sock',
          ReadOnly: true
        }]
      }
    },
    Mode: {
      Global: {}
    }
  }
});

// List services
const services = await docker.listServices();
services.forEach(svc => {
  console.log(`${svc.Spec.Name}: ${svc.Spec.Mode?.Replicated ? 'replicated' : 'global'}`);
});

Node Management

Node Instance

Node objects represent Docker Swarm nodes (managers and workers).

/**
 * Node instance representing a Docker Swarm node
 */
class Node {
  /** Node ID */
  id: string;
  /** Docker modem instance for API communication */
  modem: any;
  
  constructor(modem: any, id: string);
}

Node Operations

Manage swarm nodes and their configuration.

/**
 * Get node details and status
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to node details
 */
inspect(opts?: NodeInspectOptions, callback?: Function): Promise<NodeInspectInfo>;

/**
 * Update node configuration
 * @param opts - Update options
 * @param callback - Optional callback
 * @returns Promise resolving to update result
 */
update(opts: NodeUpdateOptions, callback?: Function): Promise<object>;

/**
 * Remove node from swarm (undocumented)
 * @param opts - Remove options
 * @param callback - Optional callback
 * @returns Promise resolving to remove result
 */
remove(opts?: NodeRemoveOptions,Callback?: Function): Promise<object>;

interface NodeInspectOptions {
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface NodeUpdateOptions {
  /** Object version for optimistic concurrency control */
  version: number;
  /** Node specification */
  Spec?: NodeSpec;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface NodeRemoveOptions {
  /** Force removal of node */
  force?: boolean;
  /** AbortSignal for request cancellation */
  abortSignal?: AbortSignal;
}

interface NodeInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Spec: NodeSpec;
  Description: NodeDescription;
  Status: NodeStatus;
  ManagerStatus?: ManagerStatus;
}

interface NodeSpec {
  /** Node name */
  Name?: string;
  /** Node labels */
  Labels?: { [key: string]: string };
  /** Node role */
  Role?: 'worker' | 'manager';
  /** Node availability */
  Availability?: 'active' | 'pause' | 'drain';
}

interface NodeDescription {
  Hostname: string;
  Platform: {
    Architecture: string;
    OS: string;
  };
  Resources: {
    NanoCPUs: number;
    MemoryBytes: number;
    GenericResources?: GenericResource[];
  };
  Engine: {
    EngineVersion: string;
    Labels?: { [key: string]: string };
    Plugins?: EnginePlugin[];
  };
  TLSInfo?: TLSInfo;
}

interface NodeStatus {
  State: 'unknown' | 'down' | 'ready' | 'disconnected';
  Message?: string;
  Addr: string;
}

interface ManagerStatus {
  Leader: boolean;
  Reachability: 'unknown' | 'unreachable' | 'reachable';
  Addr: string;
}

Usage Examples:

// Get node details
const nodeInfo = await node.inspect();
console.log(`Node: ${nodeInfo.Description.Hostname}`);
console.log(`Role: ${nodeInfo.Spec.Role}`);
console.log(`Status: ${nodeInfo.Status.State}`);
console.log(`Availability: ${nodeInfo.Spec.Availability}`);

if (nodeInfo.ManagerStatus) {
  console.log(`Manager Leader: ${nodeInfo.ManagerStatus.Leader}`);
}

// Update node (drain for maintenance)
await node.update({
  version: nodeInfo.Version.Index,
  Spec: {
    ...nodeInfo.Spec,
    Availability: 'drain'
  }
});

// List all nodes
const nodes = await docker.listNodes();
nodes.forEach(n => {
  console.log(`${n.Description.Hostname}: ${n.Spec.Role} (${n.Status.State})`);
});

Secret Management

Secret Instance

Secret objects represent Docker Swarm secrets for sensitive data.

/**
 * Secret instance representing a Docker Swarm secret
 */
class Secret {
  /** Secret ID */
  id: string;
  /** Docker modem instance for API communication */
  modem: any;
  
  constructor(modem: any, id: string);
}

Secret Operations

Manage secrets for secure data distribution.

/**
 * Get secret details (data excluded for security)
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to secret details
 */
inspect(opts?: SecretInspectOptions, callback?: Function): Promise<SecretInspectInfo>;

/**
 * Update secret configuration
 * @param opts - Update options
 * @param callback - Optional callback
 * @returns Promise resolving to update result
 */
update(opts: SecretUpdateOptions, callback?: Function): Promise<object>;

/**
 * Remove secret
 * @param opts - Remove options
 * @param callback - Optional callback
 * @returns Promise resolving to remove result
 */
remove(opts?: SecretRemoveOptions, callback?: Function): Promise<object>;

interface SecretInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Spec: SecretSpec;
}

interface SecretSpec {
  /** Secret name */
  Name?: string;
  /** Secret labels */
  Labels?: { [key: string]: string };
  /** Secret data (base64 encoded) */
  Data?: string;
  /** Driver configuration */
  Driver?: {
    Name?: string;
    Options?: { [key: string]: string };
  };
  /** Template driver */
  Templating?: {
    Name?: string;
    Options?: { [key: string]: string };
  };
}

Usage Examples:

// Create secret
const secret = await docker.createSecret({
  Spec: {
    Name: 'db-password',
    Data: Buffer.from('my-secret-password').toString('base64'),
    Labels: {
      'app': 'database'
    }
  }
});

// Get secret details (data not returned)
const secretInfo = await secret.inspect();
console.log(`Secret: ${secretInfo.Spec.Name}`);
console.log(`Created: ${secretInfo.CreatedAt}`);

// Update secret labels
await secret.update({
  version: secretInfo.Version.Index,
  Spec: {
    ...secretInfo.Spec,
    Labels: {
      ...secretInfo.Spec.Labels,
      'environment': 'production'
    }
  }
});

// Remove secret
await secret.remove();

Config Management

Config Instance

Config objects represent Docker Swarm configs for non-sensitive configuration data.

/**
 * Config instance representing a Docker Swarm config
 */
class Config {
  /** Config ID */
  id: string;
  /** Docker modem instance for API communication */
  modem: any;
  
  constructor(modem: any, id: string);
}

Config Operations

Manage configuration data distribution.

/**
 * Get config details and data
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to config details
 */
inspect(opts?: ConfigInspectOptions, callback?: Function): Promise<ConfigInspectInfo>;

/**
 * Update config
 * @param opts - Update options
 * @param callback - Optional callback
 * @returns Promise resolving to update result
 */
update(opts: ConfigUpdateOptions, callback?: Function): Promise<object>;

/**
 * Remove config
 * @param opts - Remove options
 * @param callback - Optional callback
 * @returns Promise resolving to remove result
 */
remove(opts?: ConfigRemoveOptions, callback?: Function): Promise<object>;

interface ConfigInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Spec: ConfigSpec;
}

interface ConfigSpec {
  /** Config name */
  Name?: string;
  /** Config labels */
  Labels?: { [key: string]: string };
  /** Config data (base64 encoded) */
  Data?: string;
  /** Template driver */
  Templating?: {
    Name?: string;
    Options?: { [key: string]: string };
  };
}

Usage Examples:

// Create config
const config = await docker.createConfig({
  Spec: {
    Name: 'nginx-config',
    Data: Buffer.from(`
server {
    listen 80;
    server_name localhost;
    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}
    `).toString('base64'),
    Labels: {
      'app': 'web-server'
    }
  }
});

// Get config details (includes data)
const configInfo = await config.inspect();
console.log(`Config: ${configInfo.Spec.Name}`);
const configData = Buffer.from(configInfo.Spec.Data, 'base64').toString();
console.log('Config data:', configData);

// Remove config
await config.remove();

Task Management

Task Instance

Task objects represent individual task instances within services.

/**
 * Task instance representing a Docker Swarm task
 */
class Task {
  /** Task ID */
  id: string;
  /** Docker modem instance for API communication */
  modem: any;
  
  constructor(modem: any, id: string);
}

Task Operations

Monitor and inspect individual service tasks.

/**
 * Get task details and status
 * @param opts - Inspection options
 * @param callback - Optional callback
 * @returns Promise resolving to task details
 */
inspect(opts?: TaskInspectOptions, callback?: Function): Promise<TaskInspectInfo>;

/**
 * Get task logs
 * @param opts - Log options
 * @param callback - Optional callback
 * @returns Promise resolving to log stream
 */
logs(opts?: TaskLogsOptions, callback?: Function): Promise<Stream>;

interface TaskInspectInfo {
  ID: string;
  Version: ObjectVersion;
  CreatedAt: string;
  UpdatedAt: string;
  Name: string;
  Labels: { [key: string]: string };
  Spec: TaskSpec;
  ServiceID: string;
  Slot: number;
  NodeID: string;
  AssignedGenericResources?: GenericResource[];
  Status: TaskStatus;
  DesiredState: 'new' | 'allocated' | 'pending' | 'assigned' | 'accepted' | 'preparing' | 'ready' | 'starting' | 'running' | 'complete' | 'shutdown' | 'failed' | 'rejected' | 'remove' | 'orphaned';
  NetworksAttachments?: NetworkAttachment[];
  JobIteration?: ObjectVersion;
}

interface TaskStatus {
  Timestamp: string;
  State: 'new' | 'allocated' | 'pending' | 'assigned' | 'accepted' | 'preparing' | 'ready' | 'starting' | 'running' | 'complete' | 'shutdown' | 'failed' | 'rejected' | 'remove' | 'orphaned';
  Message?: string;
  Err?: string;
  ContainerStatus?: {
    ContainerID?: string;
    PID?: number;
    ExitCode?: number;
  };
  PortStatus?: {
    Ports?: PortConfig[];
  };
}

Usage Examples:

// Get task details
const taskInfo = await task.inspect();
console.log(`Task: ${taskInfo.Name}`);
console.log(`Service: ${taskInfo.ServiceID}`);
console.log(`Node: ${taskInfo.NodeID}`);
console.log(`State: ${taskInfo.Status.State}`);

if (taskInfo.Status.ContainerStatus) {
  console.log(`Container ID: ${taskInfo.Status.ContainerStatus.ContainerID}`);
  console.log(`PID: ${taskInfo.Status.ContainerStatus.PID}`);
}

// Get task logs
const logStream = await task.logs({
  stdout: true,
  stderr: true,
  timestamps: true
});

logStream.on('data', chunk => {
  console.log(chunk.toString());
});

// List all tasks
const tasks = await docker.listTasks();
tasks.forEach(t => {
  console.log(`${t.Name}: ${t.Status.State} on ${t.NodeID}`);
});

Install with Tessl CLI

npx tessl i tessl/npm-dockerode

docs

container.md

docker-client.md

image.md

index.md

plugin.md

swarm.md

volume-network.md

tile.json