A comprehensive Python client library for the Docker Remote API enabling programmatic control of containers, images, networks, and volumes.
npx @tessl/cli install tessl/pypi-docker-py@1.10.00
# Docker-Py
1
2
A comprehensive Python client library for the Docker Remote API. It provides complete programmatic control over Docker containers, images, networks, volumes, and services from within Python applications, enabling developers to manage Docker infrastructure through Python code rather than command-line tools.
3
4
## Package Information
5
6
- **Package Name**: docker-py
7
- **Language**: Python
8
- **Installation**: `pip install docker-py`
9
- **Version**: 1.10.6
10
- **License**: Apache License 2.0
11
- **Documentation**: https://docker-py.readthedocs.io/en/latest/
12
13
## Core Imports
14
15
```python
16
import docker
17
```
18
19
Main client access:
20
21
```python
22
from docker import Client
23
```
24
25
Alternative import methods:
26
27
```python
28
# Import client classes directly
29
from docker import Client, AutoVersionClient, from_env
30
31
# Import specific functionality
32
from docker.types import LogConfig, Ulimit, Mount
33
from docker.errors import APIError, NotFound
34
```
35
36
## Basic Usage
37
38
```python
39
import docker
40
41
# Create client using default settings
42
client = docker.Client()
43
44
# Or create client from environment variables
45
client = docker.from_env()
46
47
# Pull an image
48
client.pull('ubuntu:latest')
49
50
# Create and start a container
51
container = client.create_container(
52
image='ubuntu:latest',
53
command='/bin/bash',
54
tty=True,
55
detach=True,
56
name='my-container'
57
)
58
client.start(container)
59
60
# List running containers
61
containers = client.containers()
62
print(f"Running containers: {len(containers)}")
63
64
# Get container logs
65
logs = client.logs(container)
66
print(logs.decode('utf-8'))
67
68
# Stop and remove container
69
client.stop(container)
70
client.remove_container(container)
71
72
# List and remove images
73
images = client.images()
74
client.remove_image('ubuntu:latest')
75
```
76
77
## Architecture
78
79
Docker-py uses a modular architecture built around mixins that provide specific Docker functionality:
80
81
- **Client**: Main client class inheriting from `requests.Session` and 9 API mixins
82
- **API Mixins**: Specialized classes providing Docker API functionality (containers, images, networks, etc.)
83
- **Types**: Data classes for complex Docker API objects and configurations
84
- **Utils**: Helper functions for data conversion, configuration building, and protocol handling
85
- **Transport**: Custom HTTP adapters for Unix sockets, Windows named pipes, and TLS connections
86
87
This design allows comprehensive Docker API coverage while maintaining code organization and extensibility.
88
89
## Capabilities
90
91
### Container Operations
92
93
Complete container lifecycle management including creation, startup, monitoring, and cleanup. Supports advanced features like resource constraints, networking configuration, volume mounts, and process execution within containers.
94
95
```python { .api }
96
def create_container(image, command=None, **kwargs): ...
97
def start(container, **kwargs): ...
98
def stop(container, timeout=10): ...
99
def remove_container(container, v=False, link=False, force=False): ...
100
def containers(quiet=False, all=False, **kwargs): ...
101
def inspect_container(container): ...
102
def logs(container, stdout=True, stderr=True, **kwargs): ...
103
def exec_create(container, cmd, **kwargs): ...
104
def exec_start(exec_id, **kwargs): ...
105
```
106
107
[Container Operations](./containers.md)
108
109
### Image Management
110
111
Image lifecycle operations including pulling from registries, building from Dockerfiles, tagging, pushing, and local management. Supports both public and private registries with authentication.
112
113
```python { .api }
114
def images(name=None, quiet=False, all=False, **kwargs): ...
115
def pull(repository, tag=None, **kwargs): ...
116
def push(repository, tag=None, **kwargs): ...
117
def build(path=None, tag=None, **kwargs): ...
118
def remove_image(image, force=False, noprune=False): ...
119
def inspect_image(image): ...
120
def tag(image, repository, tag=None, force=False): ...
121
```
122
123
[Image Management](./images.md)
124
125
### Network Management
126
127
Docker network operations for creating custom networks, connecting containers, and managing network isolation. Supports bridge, overlay, and custom network drivers with advanced configuration options.
128
129
```python { .api }
130
def networks(names=None, ids=None): ...
131
def create_network(name, driver=None, **kwargs): ...
132
def remove_network(net_id): ...
133
def inspect_network(net_id): ...
134
def connect_container_to_network(container, net_id, **kwargs): ...
135
def disconnect_container_from_network(container, net_id, **kwargs): ...
136
```
137
138
[Network Management](./networking.md)
139
140
### Volume Management
141
142
Docker volume operations for persistent data storage and sharing between containers. Supports named volumes, bind mounts, and volume driver configuration.
143
144
```python { .api }
145
def volumes(filters=None): ...
146
def create_volume(name, driver=None, **kwargs): ...
147
def inspect_volume(name): ...
148
def remove_volume(name): ...
149
```
150
151
### Services and Swarm
152
153
Docker Swarm cluster management and service orchestration capabilities. Provides container orchestration, service scaling, rolling updates, and cluster administration.
154
155
```python { .api }
156
def init_swarm(advertise_addr=None, **kwargs): ...
157
def join_swarm(remote_addrs, join_token, **kwargs): ...
158
def services(filters=None): ...
159
def create_service(task_template, name=None, **kwargs): ...
160
def update_service(service, version, **kwargs): ...
161
def nodes(filters=None): ...
162
```
163
164
[Services and Swarm](./swarm.md)
165
166
### System Information
167
168
Docker daemon information, version details, system events, and authentication with registries.
169
170
```python { .api }
171
def info(): ...
172
def version(api_version=True): ...
173
def ping(): ...
174
def events(since=None, until=None, **kwargs): ...
175
def login(username, password=None, **kwargs): ...
176
```
177
178
## Main Client Classes
179
180
### Client
181
182
Main Docker API client providing complete functionality through inherited mixins.
183
184
```python { .api }
185
class Client(requests.Session, *ApiMixins):
186
def __init__(self, base_url=None, version=None, timeout=60,
187
tls=False, user_agent=None, num_pools=25): ...
188
189
@classmethod
190
def from_env(cls, **kwargs): ...
191
192
@property
193
def api_version(self): ...
194
```
195
196
### AutoVersionClient
197
198
Client that automatically detects and uses the appropriate Docker API version.
199
200
```python { .api }
201
class AutoVersionClient(Client):
202
def __init__(self, *args, **kwargs): ... # version parameter not allowed
203
```
204
205
### from_env Function
206
207
Convenience function to create a client from environment variables.
208
209
```python { .api }
210
def from_env(**kwargs) -> Client:
211
"""Create Client instance from environment variables (DOCKER_HOST, etc.)"""
212
```
213
214
## Core Type Classes
215
216
### LogConfig
217
218
Container logging configuration with support for various log drivers.
219
220
```python { .api }
221
class LogConfig:
222
def __init__(self, **kwargs): ...
223
def set_config_value(self, key, value): ...
224
def unset_config(self, key): ...
225
226
# Properties
227
type: str # Log driver type
228
config: dict # Driver-specific configuration
229
230
# Log driver types
231
class LogConfigTypesEnum:
232
JSON = "json-file"
233
SYSLOG = "syslog"
234
JOURNALD = "journald"
235
GELF = "gelf"
236
FLUENTD = "fluentd"
237
NONE = "none"
238
```
239
240
### Ulimit
241
242
Process resource limits for containers.
243
244
```python { .api }
245
class Ulimit:
246
def __init__(self, **kwargs): ...
247
248
# Properties
249
name: str # Resource name (e.g., 'nofile', 'nproc')
250
soft: int # Soft limit
251
hard: int # Hard limit
252
```
253
254
### Mount
255
256
Volume mount specification for services and containers.
257
258
```python { .api }
259
class Mount:
260
def __init__(self, target, source, type='volume',
261
read_only=False, **kwargs): ...
262
263
@classmethod
264
def parse_mount_string(cls, string): ...
265
266
# Properties
267
target: str # Mount path in container
268
source: str # Source path or volume name
269
type: str # Mount type ('volume', 'bind', 'tmpfs')
270
read_only: bool # Read-only flag
271
```
272
273
## Error Classes
274
275
```python { .api }
276
class DockerException(Exception):
277
"""Base Docker exception"""
278
279
class APIError(requests.exceptions.HTTPError):
280
"""HTTP API error with Docker-specific details"""
281
def __init__(self, message, response=None, explanation=None): ...
282
def is_client_error(self) -> bool: ...
283
def is_server_error(self) -> bool: ...
284
285
class NotFound(APIError):
286
"""404 Not Found error"""
287
288
class InvalidVersion(DockerException):
289
"""Invalid API version error"""
290
291
class TLSParameterError(DockerException):
292
"""TLS configuration error"""
293
```
294
295
## Constants
296
297
```python { .api }
298
# API Configuration
299
DEFAULT_DOCKER_API_VERSION = "1.24"
300
DEFAULT_TIMEOUT_SECONDS = 60
301
DEFAULT_USER_AGENT = "docker-py/{version}"
302
DEFAULT_NUM_POOLS = 25
303
304
# Protocol
305
STREAM_HEADER_SIZE_BYTES = 8
306
IS_WINDOWS_PLATFORM = ... # Platform detection boolean
307
```
308
309
[Configuration and Utilities](./utilities.md)