511 lines
14 KiB
Markdown
511 lines
14 KiB
Markdown
# @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
|
|
|
|
```bash
|
|
# Using npm
|
|
npm install @apiclient.xyz/docker --save
|
|
|
|
# Using pnpm (recommended)
|
|
pnpm add @apiclient.xyz/docker
|
|
|
|
# Using yarn
|
|
yarn add @apiclient.xyz/docker
|
|
```
|
|
|
|
## 🎯 Quick Start
|
|
|
|
```typescript
|
|
import { DockerHost } from '@apiclient.xyz/docker';
|
|
|
|
// Connect to local Docker daemon
|
|
const docker = new DockerHost();
|
|
|
|
// Or connect to remote Docker host
|
|
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.
|
|
|
|
```typescript
|
|
import { DockerHost } from '@apiclient.xyz/docker';
|
|
|
|
// Initialize with default local socket
|
|
const docker = new DockerHost();
|
|
|
|
// Custom initialization options
|
|
const customDocker = new DockerHost({
|
|
socketPath: '/var/run/docker.sock', // Unix socket path
|
|
// or
|
|
socketPath: 'tcp://192.168.1.100:2375' // TCP connection
|
|
});
|
|
|
|
// Start and stop (for lifecycle management)
|
|
await docker.start();
|
|
// ... do your work
|
|
await docker.stop();
|
|
```
|
|
|
|
### 📦 Container Management
|
|
|
|
#### List All Containers
|
|
|
|
```typescript
|
|
// Get all containers (including stopped ones)
|
|
const allContainers = await docker.getContainers();
|
|
|
|
// Each container includes detailed information
|
|
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
|
|
|
|
```typescript
|
|
import { DockerContainer } from '@apiclient.xyz/docker';
|
|
|
|
// Create a container with detailed configuration
|
|
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, // 512MB memory limit
|
|
},
|
|
Env: [
|
|
'NODE_ENV=production',
|
|
'LOG_LEVEL=info'
|
|
],
|
|
Labels: {
|
|
'app': 'web-server',
|
|
'environment': 'production'
|
|
}
|
|
});
|
|
|
|
console.log(`Container created: ${container.Id}`);
|
|
|
|
// Container operations (these would need to be implemented)
|
|
// await container.start();
|
|
// await container.stop();
|
|
// await container.remove();
|
|
```
|
|
|
|
#### Get Container by ID
|
|
|
|
```typescript
|
|
const container = await DockerContainer.getContainerById(docker, 'container-id-here');
|
|
if (container) {
|
|
console.log(`Found container: ${container.Names[0]}`);
|
|
}
|
|
```
|
|
|
|
### 🖼️ Image Management
|
|
|
|
#### Pull Images from Registry
|
|
|
|
```typescript
|
|
import { DockerImage } from '@apiclient.xyz/docker';
|
|
|
|
// Pull an image from Docker Hub
|
|
const image = await DockerImage.createFromRegistry(docker, {
|
|
imageName: 'node',
|
|
imageTag: '18-alpine',
|
|
// Optional: provide registry authentication
|
|
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
|
|
|
|
```typescript
|
|
import * as fs from 'fs';
|
|
|
|
// Import from a tar stream
|
|
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
|
|
|
|
```typescript
|
|
// Export an image to a tar stream
|
|
const image = await DockerImage.getImageByName(docker, 'nginx:latest');
|
|
const exportStream = await image.exportToTarStream();
|
|
|
|
// Save to file
|
|
const writeStream = fs.createWriteStream('./nginx-export.tar');
|
|
exportStream.pipe(writeStream);
|
|
```
|
|
|
|
#### Tag Images
|
|
|
|
```typescript
|
|
// Tag an existing image
|
|
await DockerImage.tagImageByIdOrName(docker, 'node:18-alpine', {
|
|
registry: 'myregistry.com',
|
|
imageName: 'my-node-app',
|
|
imageTag: 'v2.0.0'
|
|
});
|
|
// Result: myregistry.com/my-node-app:v2.0.0
|
|
```
|
|
|
|
### 🌐 Network Management
|
|
|
|
#### Create Custom Networks
|
|
|
|
```typescript
|
|
import { DockerNetwork } from '@apiclient.xyz/docker';
|
|
|
|
// Create a bridge network
|
|
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
|
|
|
|
```typescript
|
|
// Get all 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}`);
|
|
});
|
|
|
|
// Get specific network
|
|
const appNetwork = await DockerNetwork.getNetworkByName(docker, 'my-app-network');
|
|
|
|
// Get containers on network
|
|
const containers = await appNetwork.getContainersOnNetwork();
|
|
console.log(`Containers on network: ${containers.length}`);
|
|
```
|
|
|
|
### 🎭 Service Management (Swarm Mode)
|
|
|
|
#### Deploy Services
|
|
|
|
```typescript
|
|
import { DockerService } from '@apiclient.xyz/docker';
|
|
|
|
// Create a replicated service
|
|
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, // 256MB
|
|
CPUs: 0.5
|
|
}
|
|
},
|
|
secrets: ['api-key', 'db-password'],
|
|
mounts: [{
|
|
Target: '/data',
|
|
Source: 'app-data',
|
|
Type: 'volume'
|
|
}]
|
|
});
|
|
|
|
console.log(`Service deployed: ${service.ID}`);
|
|
```
|
|
|
|
#### Manage Services
|
|
|
|
```typescript
|
|
// List all 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}`);
|
|
});
|
|
|
|
// Get service by name
|
|
const myService = await DockerService.getServiceByName(docker, 'web-api');
|
|
|
|
// Check if service needs update
|
|
const needsUpdate = await myService.needsUpdate();
|
|
if (needsUpdate) {
|
|
console.log('Service configuration has changed, update needed');
|
|
}
|
|
|
|
// Remove service
|
|
await myService.remove();
|
|
```
|
|
|
|
### 🔐 Secrets Management
|
|
|
|
```typescript
|
|
import { DockerSecret } from '@apiclient.xyz/docker';
|
|
|
|
// Create a secret
|
|
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}`);
|
|
|
|
// List secrets
|
|
const secrets = await DockerSecret.getSecrets(docker);
|
|
secrets.forEach(secret => {
|
|
console.log(`Secret: ${secret.Spec.Name}`);
|
|
});
|
|
|
|
// Get secret by name
|
|
const apiKeySecret = await DockerSecret.getSecretByName(docker, 'api-key');
|
|
|
|
// Update secret
|
|
await apiKeySecret.update({
|
|
data: Buffer.from('new-secret-key-456').toString('base64')
|
|
});
|
|
|
|
// Remove secret
|
|
await apiKeySecret.remove();
|
|
```
|
|
|
|
### 💾 S3 Image Storage
|
|
|
|
Store and retrieve Docker images from S3-compatible storage:
|
|
|
|
```typescript
|
|
// Configure S3 storage
|
|
await docker.addS3Storage({
|
|
endpoint: 's3.amazonaws.com',
|
|
accessKeyId: 'your-access-key',
|
|
secretAccessKey: 'your-secret-key',
|
|
bucket: 'docker-images'
|
|
});
|
|
|
|
// Store an image to S3
|
|
const imageStore = docker.imageStore;
|
|
await imageStore.storeImage('my-app:v1.0.0');
|
|
|
|
// Retrieve an image from S3
|
|
const retrievedImage = await imageStore.getImage('my-app:v1.0.0');
|
|
```
|
|
|
|
### 📊 Event Monitoring
|
|
|
|
Monitor Docker events in real-time using RxJS observables:
|
|
|
|
```typescript
|
|
// Subscribe to Docker events
|
|
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')
|
|
});
|
|
|
|
// Unsubscribe when done
|
|
subscription.unsubscribe();
|
|
```
|
|
|
|
### 🔧 Registry Authentication
|
|
|
|
Authenticate with Docker registries for private images:
|
|
|
|
```typescript
|
|
// Authenticate with Docker Hub
|
|
await docker.auth({
|
|
username: 'your-username',
|
|
password: 'your-password',
|
|
serveraddress: 'https://index.docker.io/v1/'
|
|
});
|
|
|
|
// Or use existing Docker config
|
|
const authToken = await docker.getAuthTokenFromDockerConfig('myregistry.com');
|
|
|
|
// Use auth token when pulling images
|
|
const privateImage = await DockerImage.createFromRegistry(docker, {
|
|
imageName: 'myregistry.com/private/image',
|
|
imageTag: 'latest',
|
|
authToken
|
|
});
|
|
```
|
|
|
|
### 🔄 Swarm Mode
|
|
|
|
Initialize and manage Docker Swarm:
|
|
|
|
```typescript
|
|
// Initialize swarm mode
|
|
await docker.activateSwarm({
|
|
ListenAddr: '0.0.0.0:2377',
|
|
AdvertiseAddr: '192.168.1.100:2377',
|
|
ForceNewCluster: false
|
|
});
|
|
|
|
// Now you can create services, secrets, and use swarm features
|
|
const service = await DockerService.createService(docker, {
|
|
name: 'my-swarm-service',
|
|
image: 'nginx:latest',
|
|
replicas: 5
|
|
// ... more service config
|
|
});
|
|
```
|
|
|
|
## 🏗️ Advanced Examples
|
|
|
|
### Complete Application Stack
|
|
|
|
```typescript
|
|
async function deployStack() {
|
|
const docker = new DockerHost();
|
|
|
|
// Create network
|
|
const network = await DockerNetwork.createNetwork(docker, {
|
|
Name: 'app-network',
|
|
Driver: 'overlay' // for swarm mode
|
|
});
|
|
|
|
// Create secrets
|
|
const dbPassword = await DockerSecret.createSecret(docker, {
|
|
name: 'db-password',
|
|
data: Buffer.from('strong-password').toString('base64')
|
|
});
|
|
|
|
// Deploy database service
|
|
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']
|
|
});
|
|
|
|
// Deploy application service
|
|
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:
|
|
|
|
```typescript
|
|
import type {
|
|
IContainerCreationDescriptor,
|
|
IServiceCreationDescriptor,
|
|
INetworkCreationDescriptor,
|
|
IImageCreationDescriptor,
|
|
ISecretCreationDescriptor
|
|
} from '@apiclient.xyz/docker';
|
|
|
|
// Full IntelliSense support for all configuration options
|
|
const containerConfig: IContainerCreationDescriptor = {
|
|
Image: 'node:18',
|
|
// Your IDE will provide full autocomplete here
|
|
};
|
|
```
|
|
|
|
## 🤝 Contributing
|
|
|
|
We welcome contributions! Please feel free to submit issues and pull requests.
|
|
|
|
## 📖 API Documentation
|
|
|
|
For complete API documentation, visit [https://apiclient.xyz/docker](https://apiclient.xyz/docker)
|
|
|
|
For Docker Remote API reference, see [Docker Engine API Documentation](https://docs.docker.com/engine/api/latest/)
|
|
|
|
## 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](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. |