@apiclient.xyz/docker 🐳
Powerful TypeScript client for Docker Remote API - Build, manage, and orchestrate Docker containers, images, networks, and more with type-safe elegance.
🚀 Features
- 🎯 Full TypeScript Support - Complete type definitions for Docker API entities
- 🔄 Async/Await Ready - Modern promise-based architecture for seamless async operations
- 📦 Container Management - Create, list, inspect, and remove containers effortlessly
- 🖼️ Image Handling - Pull from registries, build from tarballs, export, and manage tags
- 🌐 Network Operations - Create and manage Docker networks with full IPAM support
- 🔐 Secrets Management - Handle Docker secrets securely in swarm mode
- 🎭 Service Orchestration - Deploy and manage services in Docker Swarm
- 💾 S3 Image Storage - Built-in support for storing/retrieving images from S3
- 📊 Event Streaming - Real-time Docker event monitoring with RxJS observables
- 🔧 Registry Authentication - Seamless authentication with Docker registries
📦 Installation
npm install @apiclient.xyz/docker --save
pnpm add @apiclient.xyz/docker
yarn add @apiclient.xyz/docker
🎯 Quick Start
import { DockerHost } from '@apiclient.xyz/docker';
const docker = new DockerHost();
const remoteDocker = new DockerHost({
socketPath: 'tcp://remote-docker-host:2375'
});
📚 Complete API Guide
🐳 DockerHost - Your Gateway to Docker
The DockerHost
class is your primary interface to interact with the Docker daemon.
import { DockerHost } from '@apiclient.xyz/docker';
const docker = new DockerHost();
const customDocker = new DockerHost({
socketPath: '/var/run/docker.sock',
socketPath: 'tcp://192.168.1.100:2375'
});
await docker.start();
await docker.stop();
📦 Container Management
List All Containers
const allContainers = await docker.getContainers();
allContainers.forEach(container => {
console.log(`Container: ${container.Names[0]}`);
console.log(` ID: ${container.Id}`);
console.log(` Status: ${container.Status}`);
console.log(` Image: ${container.Image}`);
console.log(` State: ${container.State}`);
});
Create and Manage Containers
import { DockerContainer } from '@apiclient.xyz/docker';
const container = await DockerContainer.create(docker, {
Image: 'nginx:latest',
name: 'my-nginx-server',
HostConfig: {
PortBindings: {
'80/tcp': [{ HostPort: '8080' }]
},
RestartPolicy: {
Name: 'unless-stopped'
},
Memory: 512 * 1024 * 1024,
},
Env: [
'NODE_ENV=production',
'LOG_LEVEL=info'
],
Labels: {
'app': 'web-server',
'environment': 'production'
}
});
console.log(`Container created: ${container.Id}`);
Get Container by ID
const container = await DockerContainer.getContainerById(docker, 'container-id-here');
if (container) {
console.log(`Found container: ${container.Names[0]}`);
}
🖼️ Image Management
Pull Images from Registry
import { DockerImage } from '@apiclient.xyz/docker';
const image = await DockerImage.createFromRegistry(docker, {
imageName: 'node',
imageTag: '18-alpine',
authToken: 'your-registry-auth-token'
});
console.log(`Image pulled: ${image.RepoTags[0]}`);
console.log(`Size: ${(image.Size / 1024 / 1024).toFixed(2)} MB`);
Import Images from Tar
import * as fs from 'fs';
const tarStream = fs.createReadStream('./my-image.tar');
const importedImage = await DockerImage.createFromTarStream(docker, {
tarStream,
imageUrl: 'file://./my-image.tar',
imageTag: 'my-app:v1.0.0'
});
Export Images to Tar
const image = await DockerImage.getImageByName(docker, 'nginx:latest');
const exportStream = await image.exportToTarStream();
const writeStream = fs.createWriteStream('./nginx-export.tar');
exportStream.pipe(writeStream);
Tag Images
await DockerImage.tagImageByIdOrName(docker, 'node:18-alpine', {
registry: 'myregistry.com',
imageName: 'my-node-app',
imageTag: 'v2.0.0'
});
🌐 Network Management
Create Custom Networks
import { DockerNetwork } from '@apiclient.xyz/docker';
const network = await DockerNetwork.createNetwork(docker, {
Name: 'my-app-network',
Driver: 'bridge',
EnableIPv6: false,
IPAM: {
Driver: 'default',
Config: [{
Subnet: '172.28.0.0/16',
Gateway: '172.28.0.1'
}]
},
Labels: {
'project': 'my-app',
'environment': 'production'
}
});
console.log(`Network created: ${network.Id}`);
List and Inspect Networks
const networks = await docker.getNetworks();
networks.forEach(net => {
console.log(`Network: ${net.Name} (${net.Driver})`);
console.log(` Scope: ${net.Scope}`);
console.log(` Internal: ${net.Internal}`);
});
const appNetwork = await DockerNetwork.getNetworkByName(docker, 'my-app-network');
const containers = await appNetwork.getContainersOnNetwork();
console.log(`Containers on network: ${containers.length}`);
🎭 Service Management (Swarm Mode)
Deploy Services
import { DockerService } from '@apiclient.xyz/docker';
const service = await DockerService.createService(docker, {
name: 'web-api',
image: 'my-api:latest',
replicas: 3,
ports: [{
Protocol: 'tcp',
PublishedPort: 80,
TargetPort: 3000
}],
networks: ['my-app-network'],
labels: {
'app': 'api',
'version': '2.0.0'
},
resources: {
limits: {
Memory: 256 * 1024 * 1024,
CPUs: 0.5
}
},
secrets: ['api-key', 'db-password'],
mounts: [{
Target: '/data',
Source: 'app-data',
Type: 'volume'
}]
});
console.log(`Service deployed: ${service.ID}`);
Manage Services
const services = await docker.getServices();
services.forEach(service => {
console.log(`Service: ${service.Spec.Name}`);
console.log(` Replicas: ${service.Spec.Mode.Replicated.Replicas}`);
console.log(` Image: ${service.Spec.TaskTemplate.ContainerSpec.Image}`);
});
const myService = await DockerService.getServiceByName(docker, 'web-api');
const needsUpdate = await myService.needsUpdate();
if (needsUpdate) {
console.log('Service configuration has changed, update needed');
}
await myService.remove();
🔐 Secrets Management
import { DockerSecret } from '@apiclient.xyz/docker';
const secret = await DockerSecret.createSecret(docker, {
name: 'api-key',
data: Buffer.from('super-secret-key-123').toString('base64'),
labels: {
'app': 'my-app',
'type': 'api-key'
}
});
console.log(`Secret created: ${secret.ID}`);
const secrets = await DockerSecret.getSecrets(docker);
secrets.forEach(secret => {
console.log(`Secret: ${secret.Spec.Name}`);
});
const apiKeySecret = await DockerSecret.getSecretByName(docker, 'api-key');
await apiKeySecret.update({
data: Buffer.from('new-secret-key-456').toString('base64')
});
await apiKeySecret.remove();
💾 S3 Image Storage
Store and retrieve Docker images from S3-compatible storage:
await docker.addS3Storage({
endpoint: 's3.amazonaws.com',
accessKeyId: 'your-access-key',
secretAccessKey: 'your-secret-key',
bucket: 'docker-images'
});
const imageStore = docker.imageStore;
await imageStore.storeImage('my-app:v1.0.0');
const retrievedImage = await imageStore.getImage('my-app:v1.0.0');
📊 Event Monitoring
Monitor Docker events in real-time using RxJS observables:
const eventStream = docker.getEventObservable();
const subscription = eventStream.subscribe({
next: (event) => {
console.log(`Event: ${event.Type} - ${event.Action}`);
console.log(`Actor: ${event.Actor.ID}`);
console.log(`Time: ${new Date(event.time * 1000).toISOString()}`);
},
error: (err) => console.error('Event stream error:', err),
complete: () => console.log('Event stream completed')
});
subscription.unsubscribe();
🔧 Registry Authentication
Authenticate with Docker registries for private images:
await docker.auth({
username: 'your-username',
password: 'your-password',
serveraddress: 'https://index.docker.io/v1/'
});
const authToken = await docker.getAuthTokenFromDockerConfig('myregistry.com');
const privateImage = await DockerImage.createFromRegistry(docker, {
imageName: 'myregistry.com/private/image',
imageTag: 'latest',
authToken
});
🔄 Swarm Mode
Initialize and manage Docker Swarm:
await docker.activateSwarm({
ListenAddr: '0.0.0.0:2377',
AdvertiseAddr: '192.168.1.100:2377',
ForceNewCluster: false
});
const service = await DockerService.createService(docker, {
name: 'my-swarm-service',
image: 'nginx:latest',
replicas: 5
});
🏗️ Advanced Examples
Complete Application Stack
async function deployStack() {
const docker = new DockerHost();
const network = await DockerNetwork.createNetwork(docker, {
Name: 'app-network',
Driver: 'overlay'
});
const dbPassword = await DockerSecret.createSecret(docker, {
name: 'db-password',
data: Buffer.from('strong-password').toString('base64')
});
const dbService = await DockerService.createService(docker, {
name: 'postgres',
image: 'postgres:14',
networks: ['app-network'],
secrets: ['db-password'],
env: ['POSTGRES_PASSWORD_FILE=/run/secrets/db-password']
});
const appService = await DockerService.createService(docker, {
name: 'web-app',
image: 'my-app:latest',
replicas: 3,
networks: ['app-network'],
ports: [{ Protocol: 'tcp', PublishedPort: 80, TargetPort: 3000 }]
});
console.log('Stack deployed successfully!');
}
🔍 TypeScript Support
This package provides comprehensive TypeScript definitions for all Docker API entities:
import type {
IContainerCreationDescriptor,
IServiceCreationDescriptor,
INetworkCreationDescriptor,
IImageCreationDescriptor,
ISecretCreationDescriptor
} from '@apiclient.xyz/docker';
const containerConfig: IContainerCreationDescriptor = {
Image: 'node:18',
};
🤝 Contributing
We welcome contributions! Please feel free to submit issues and pull requests.
📖 API Documentation
For complete API documentation, visit https://apiclient.xyz/docker
For Docker Remote API reference, see Docker Engine API Documentation
License and Legal Information
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the license file within this repository.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
Trademarks
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
Company Information
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.