A Python library for the Docker Engine API.
npx @tessl/cli install tessl/pypi-docker@7.1.00
# Docker Python Library
1
2
A comprehensive Python library for interacting with the Docker Engine API, enabling developers to perform all Docker operations programmatically from within Python applications. It offers both high-level client interfaces and low-level API access for managing containers, images, networks, volumes, and Docker Swarm services.
3
4
## Package Information
5
6
- **Package Name**: docker
7
- **Language**: Python
8
- **Installation**: `pip install docker`
9
- **Optional Dependencies**:
10
- `pip install docker[ssh]` for SSH connections
11
- `pip install docker[websockets]` for WebSocket attach support
12
13
## Core Imports
14
15
```python
16
import docker
17
18
# Access version information
19
print(docker.__version__)
20
```
21
22
Create a client:
23
24
```python
25
# High-level client (recommended)
26
client = docker.DockerClient(base_url='unix:///var/run/docker.sock')
27
28
# Or from environment variables
29
client = docker.from_env()
30
31
# Low-level API client
32
api_client = docker.APIClient(base_url='unix:///var/run/docker.sock')
33
```
34
35
## Basic Usage
36
37
```python
38
import docker
39
40
# Create client from environment
41
client = docker.from_env()
42
43
# Pull an image
44
client.images.pull('hello-world')
45
46
# Run a container
47
container = client.containers.run(
48
'hello-world',
49
detach=True,
50
name='my-hello-world'
51
)
52
53
# Check container status
54
print(container.status)
55
56
# Get container logs
57
logs = container.logs()
58
print(logs.decode('utf-8'))
59
60
# Stop and remove container
61
container.stop()
62
container.remove()
63
64
# List all containers
65
containers = client.containers.list(all=True)
66
for container in containers:
67
print(f"{container.name}: {container.status}")
68
69
# Build image from Dockerfile
70
image = client.images.build(
71
path='/path/to/dockerfile/directory',
72
tag='my-custom-image:latest'
73
)
74
```
75
76
## Architecture
77
78
The Docker Python library provides two main interface levels:
79
80
- **High-level Interface** (`DockerClient`): Object-oriented resource collections with convenient methods
81
- **Low-level Interface** (`APIClient`): Direct Docker Engine API access with full control
82
83
**Resource Collections** manage Docker objects:
84
- **Containers**: Running application instances
85
- **Images**: Filesystem snapshots and templates
86
- **Networks**: Container networking configurations
87
- **Volumes**: Persistent data storage
88
- **Services**: Docker Swarm service definitions
89
90
This design enables both simple scripting and complex Docker orchestration workflows.
91
92
## Capabilities
93
94
### Client Management
95
96
High-level and low-level client interfaces for connecting to Docker Engine with support for various connection methods including Unix sockets, TCP, SSH tunnels, and TLS authentication.
97
98
```python { .api }
99
class DockerClient:
100
def __init__(self, *args, **kwargs): ...
101
102
@classmethod
103
def from_env(cls, **kwargs): ...
104
105
def close(self): ...
106
def df(self): ...
107
def info(self): ...
108
def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs): ...
109
def ping(self): ...
110
def version(self, api_version=True): ...
111
def events(self, since=None, until=None, filters=None, decode=None): ...
112
113
def from_env(**kwargs): ...
114
115
class APIClient:
116
def __init__(self, base_url=None, version=None, timeout=60, tls=False, user_agent=None, num_pools=None, credstore_env=None, use_ssh_client=False, max_pool_size=10): ...
117
def reload_config(self, dockercfg_path=None): ...
118
```
119
120
[Client Management](./client-management.md)
121
122
### Container Management
123
124
Complete container lifecycle management including creation, execution, monitoring, and resource control with support for advanced features like container attachment, file transfer, and process execution.
125
126
```python { .api }
127
class ContainerCollection:
128
def run(self, image, command=None, **kwargs): ...
129
def create(self, image, command=None, **kwargs): ...
130
def get(self, container_id): ...
131
def list(self, all=False, before=None, filters=None, **kwargs): ...
132
def prune(self, filters=None): ...
133
134
class Container:
135
def start(self, **kwargs): ...
136
def stop(self, timeout=10): ...
137
def restart(self, timeout=10): ...
138
def kill(self, signal='SIGKILL'): ...
139
def pause(self): ...
140
def unpause(self): ...
141
def remove(self, v=False, link=False, force=False): ...
142
def exec_run(self, cmd, **kwargs): ...
143
def logs(self, **kwargs): ...
144
def stats(self, decode=None, stream=True): ...
145
def attach(self, **kwargs): ...
146
def commit(self, repository=None, tag=None, **kwargs): ...
147
```
148
149
[Container Management](./container-management.md)
150
151
### Image Management
152
153
Docker image operations including building, pulling, pushing, tagging, and registry interactions with support for multi-platform builds and custom build contexts.
154
155
```python { .api }
156
class ImageCollection:
157
def build(self, **kwargs): ...
158
def get(self, name): ...
159
def get_registry_data(self, name, auth_config=None): ...
160
def list(self, name=None, all=False, filters=None): ...
161
def load(self, data): ...
162
def pull(self, repository, tag=None, all_tags=False, **kwargs): ...
163
def push(self, repository, tag=None, **kwargs): ...
164
def search(self, term, **kwargs): ...
165
def prune(self, filters=None): ...
166
def prune_builds(self, **kwargs): ...
167
168
class Image:
169
def history(self): ...
170
def reload(self): ...
171
def remove(self, force=False, noprune=False): ...
172
def save(self, chunk_size=2097152): ...
173
def tag(self, repository, tag=None, **kwargs): ...
174
```
175
176
[Image Management](./image-management.md)
177
178
### Network Management
179
180
Docker network creation, configuration, and container connectivity management with support for custom networks, network drivers, and advanced networking features.
181
182
```python { .api }
183
class NetworkCollection:
184
def create(self, name, **kwargs): ...
185
def get(self, network_id): ...
186
def list(self, names=None, ids=None, filters=None): ...
187
def prune(self, filters=None): ...
188
189
class Network:
190
def connect(self, container, **kwargs): ...
191
def disconnect(self, container, **kwargs): ...
192
def remove(self): ...
193
```
194
195
[Network Management](./network-management.md)
196
197
### Volume Management
198
199
Docker volume operations for persistent data storage including volume creation, mounting, and lifecycle management with support for volume drivers and custom configurations.
200
201
```python { .api }
202
class VolumeCollection:
203
def create(self, name=None, **kwargs): ...
204
def get(self, volume_id): ...
205
def list(self, filters=None): ...
206
def prune(self, filters=None): ...
207
208
class Volume:
209
def remove(self, force=False): ...
210
```
211
212
[Volume Management](./volume-management.md)
213
214
### Docker Swarm Services
215
216
Docker Swarm service orchestration including service creation, scaling, updating, and management with support for service constraints, placement preferences, and rolling updates.
217
218
```python { .api }
219
class ServiceCollection:
220
def create(self, image, **kwargs): ...
221
def get(self, service_id): ...
222
def list(self, filters=None): ...
223
224
class Service:
225
def logs(self, **kwargs): ...
226
def remove(self): ...
227
def scale(self, replicas): ...
228
def update(self, **kwargs): ...
229
```
230
231
[Docker Swarm Services](./swarm-services.md)
232
233
### Configuration and Secrets
234
235
Docker configuration and secret management for secure credential handling and application configuration with support for external secret stores and configuration templating.
236
237
```python { .api }
238
class ConfigCollection:
239
def create(self, **kwargs): ...
240
def get(self, config_id): ...
241
def list(self, filters=None): ...
242
243
class SecretCollection:
244
def create(self, **kwargs): ...
245
def get(self, secret_id): ...
246
def list(self, filters=None): ...
247
248
class Config:
249
def remove(self): ...
250
251
class Secret:
252
def remove(self): ...
253
```
254
255
[Configuration and Secrets](./config-secrets.md)
256
257
### Plugin Management
258
259
Docker plugin installation, configuration, and lifecycle management with support for volume drivers, network drivers, and custom plugin development.
260
261
```python { .api }
262
class PluginCollection:
263
def create(self, **kwargs): ...
264
def get(self, name): ...
265
def list(self, filters=None): ...
266
def install(self, remote_name, local_name=None): ...
267
268
class Plugin:
269
def configure(self, options): ...
270
def disable(self, **kwargs): ...
271
def enable(self, timeout=0): ...
272
def push(self, **kwargs): ...
273
def remove(self, **kwargs): ...
274
def upgrade(self, **kwargs): ...
275
```
276
277
[Plugin Management](./plugin-management.md)
278
279
### System Information and Events
280
281
Docker daemon system information, resource usage monitoring, and real-time event streaming for comprehensive Docker environment observability.
282
283
```python { .api }
284
def df(self): ...
285
def info(self): ...
286
def ping(self): ...
287
def version(self, api_version=True): ...
288
def events(self, since=None, until=None, filters=None, decode=None): ...
289
```
290
291
[System Information and Events](./system-events.md)
292
293
### Context Management
294
295
Docker context management for connecting to different Docker hosts and orchestrators with persistent configuration and credential storage.
296
297
```python { .api }
298
class Context:
299
def __init__(self, name, orchestrator=None, host=None, endpoints=None, tls=False): ...
300
def set_endpoint(self, name='docker', host=None, tls_cfg=None, skip_tls_verify=False, def_namespace=None): ...
301
def inspect(self): ...
302
def save(self): ...
303
def remove(self): ...
304
305
@classmethod
306
def load_context(cls, name): ...
307
308
class ContextAPI:
309
@classmethod
310
def create_context(cls, name, orchestrator=None, host=None, tls_cfg=None, default_namespace=None, skip_tls_verify=False): ...
311
312
@classmethod
313
def get_context(cls, name=None): ...
314
315
@classmethod
316
def list_contexts(cls): ...
317
318
@classmethod
319
def remove_context(cls, name): ...
320
321
@classmethod
322
def get_current_context_name(cls): ...
323
```
324
325
[Context Management](./context-management.md)
326
327
### Error Handling
328
329
Comprehensive exception hierarchy for robust error handling and debugging with specific exceptions for different failure scenarios.
330
331
```python { .api }
332
class DockerException(Exception): ...
333
class APIError(requests.exceptions.HTTPError, DockerException): ...
334
class NotFound(APIError): ...
335
class ImageNotFound(NotFound): ...
336
class ContainerError(DockerException): ...
337
class BuildError(DockerException): ...
338
class TLSParameterError(DockerException): ...
339
```
340
341
[Error Handling](./error-handling.md)
342
343
## Types
344
345
```python { .api }
346
class TLSConfig:
347
def __init__(self, client_cert=None, ca_cert=None, verify=None): ...
348
def configure_client(self, client): ...
349
```