0
# Client Management
1
2
Client interfaces for connecting to Docker Engine with support for various connection methods, authentication, and configuration options.
3
4
## Capabilities
5
6
### High-Level DockerClient
7
8
The main client interface providing resource collections and convenient methods for Docker operations.
9
10
```python { .api }
11
class DockerClient:
12
def __init__(self, base_url='unix:///var/run/docker.sock', version='auto', timeout=60, tls=False, user_agent=None, credstore_env=None, use_ssh_client=False, max_pool_size=10):
13
"""
14
Create a DockerClient instance.
15
16
Args:
17
base_url (str): URL to the Docker server. Examples:
18
- 'unix:///var/run/docker.sock' (Unix socket)
19
- 'tcp://127.0.0.1:2376' (TCP connection)
20
- 'ssh://user@host' (SSH connection)
21
version (str): API version to use ('auto' for auto-detection)
22
timeout (int): Default timeout for API calls in seconds
23
tls (bool or TLSConfig): Enable TLS. True for default TLS, TLSConfig for custom
24
user_agent (str): Custom user agent for requests
25
credstore_env (dict): Environment variables for credential store
26
use_ssh_client (bool): Use SSH client for connections
27
max_pool_size (int): Maximum connection pool size
28
"""
29
```
30
31
#### Class Methods
32
33
```python { .api }
34
@classmethod
35
def from_env(cls, **kwargs):
36
"""
37
Create a client configured from environment variables.
38
39
Uses DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH environment variables.
40
41
Returns:
42
DockerClient: Configured client instance
43
"""
44
```
45
46
#### System Operations
47
48
```python { .api }
49
def close(self):
50
"""Close the client connection and clean up resources."""
51
52
def df(self):
53
"""
54
Get Docker system disk usage information.
55
56
Returns:
57
dict: Disk usage data including images, containers, volumes, build cache
58
"""
59
60
def info(self):
61
"""
62
Get Docker system information.
63
64
Returns:
65
dict: System information including version, storage driver, kernel version
66
"""
67
68
def ping(self):
69
"""
70
Ping the Docker daemon.
71
72
Returns:
73
bool: True if daemon is reachable
74
75
Raises:
76
APIError: If daemon is unreachable
77
"""
78
79
def version(self, api_version=True):
80
"""
81
Get Docker version information.
82
83
Args:
84
api_version (bool): Include API version information
85
86
Returns:
87
dict: Version information including Docker version, API version, Git commit
88
"""
89
```
90
91
#### Authentication
92
93
```python { .api }
94
def login(self, username, password=None, email=None, registry=None, reauth=False, **kwargs):
95
"""
96
Authenticate with a Docker registry.
97
98
Args:
99
username (str): Registry username
100
password (str): Registry password (prompted if None)
101
email (str): Registry email (optional)
102
registry (str): Registry URL (defaults to Docker Hub)
103
reauth (bool): Force re-authentication
104
105
Returns:
106
dict: Authentication response
107
108
Raises:
109
APIError: If authentication fails
110
"""
111
```
112
113
#### Event Streaming
114
115
```python { .api }
116
def events(self, since=None, until=None, filters=None, decode=None):
117
"""
118
Stream Docker events from the daemon.
119
120
Args:
121
since (datetime or str): Show events since this time
122
until (datetime or str): Show events until this time
123
filters (dict): Event filters by type, container, image, etc.
124
decode (bool): Decode JSON events automatically
125
126
Yields:
127
dict: Event objects containing action, type, time, actor information
128
"""
129
```
130
131
#### Resource Collections
132
133
The DockerClient provides access to resource collections:
134
135
```python { .api }
136
@property
137
def containers(self):
138
"""ContainerCollection: Container management operations"""
139
140
@property
141
def images(self):
142
"""ImageCollection: Image management operations"""
143
144
@property
145
def networks(self):
146
"""NetworkCollection: Network management operations"""
147
148
@property
149
def volumes(self):
150
"""VolumeCollection: Volume management operations"""
151
152
@property
153
def services(self):
154
"""ServiceCollection: Docker Swarm service operations"""
155
156
@property
157
def configs(self):
158
"""ConfigCollection: Docker config management"""
159
160
@property
161
def secrets(self):
162
"""SecretCollection: Docker secret management"""
163
164
@property
165
def plugins(self):
166
"""PluginCollection: Plugin management operations"""
167
168
@property
169
def nodes(self):
170
"""NodeCollection: Swarm node management"""
171
172
@property
173
def swarm(self):
174
"""Swarm: Swarm cluster management"""
175
```
176
177
### Low-Level APIClient
178
179
Direct Docker Engine API access for advanced use cases requiring full control.
180
181
```python { .api }
182
class APIClient:
183
def __init__(self, base_url='unix:///var/run/docker.sock', version='auto', timeout=60, tls=False, user_agent=None, credstore_env=None, use_ssh_client=False, max_pool_size=10):
184
"""
185
Create an APIClient instance with the same parameters as DockerClient.
186
187
This client inherits from requests.Session and provides direct access
188
to Docker Engine API endpoints.
189
"""
190
191
def reload_config(self, dockercfg_path=None):
192
"""
193
Reload authentication configuration from Docker config file.
194
195
Args:
196
dockercfg_path (str): Path to Docker config file (optional)
197
"""
198
199
@property
200
def api_version(self):
201
"""str: Current Docker API version being used"""
202
203
@property
204
def base_url(self):
205
"""str: Base URL of the Docker daemon"""
206
207
@property
208
def timeout(self):
209
"""int: Request timeout in seconds"""
210
```
211
212
### Factory Function
213
214
```python { .api }
215
def from_env(**kwargs):
216
"""
217
Create a DockerClient configured from environment variables.
218
219
Convenience function equivalent to DockerClient.from_env().
220
221
Args:
222
**kwargs: Additional arguments passed to DockerClient constructor
223
224
Returns:
225
DockerClient: Configured client instance
226
"""
227
```
228
229
### TLS Configuration
230
231
```python { .api }
232
class TLSConfig:
233
def __init__(self, client_cert=None, ca_cert=None, verify=None):
234
"""
235
TLS configuration for secure Docker connections.
236
237
Args:
238
client_cert (tuple): (cert_path, key_path) for client certificate
239
ca_cert (str): Path to CA certificate file
240
verify (bool or str): Verify server certificate. True uses ca_cert,
241
str path uses custom CA, False disables verification
242
"""
243
244
def configure_client(self, client):
245
"""
246
Configure a requests client with TLS settings.
247
248
Args:
249
client: requests.Session object to configure
250
"""
251
```
252
253
## Usage Examples
254
255
### Basic Client Creation
256
257
```python
258
import docker
259
260
# From environment variables (recommended)
261
client = docker.from_env()
262
263
# Custom connection
264
client = docker.DockerClient(
265
base_url='tcp://192.168.1.100:2376',
266
timeout=30
267
)
268
269
# SSH connection
270
client = docker.DockerClient(
271
base_url='ssh://user@remote-host',
272
use_ssh_client=True
273
)
274
```
275
276
### TLS Configuration
277
278
```python
279
import docker
280
281
# Basic TLS
282
client = docker.DockerClient(
283
base_url='tcp://192.168.1.100:2376',
284
tls=True
285
)
286
287
# Custom TLS configuration
288
tls_config = docker.TLSConfig(
289
client_cert=('/path/to/cert.pem', '/path/to/key.pem'),
290
ca_cert='/path/to/ca.pem',
291
verify=True
292
)
293
294
client = docker.DockerClient(
295
base_url='tcp://192.168.1.100:2376',
296
tls=tls_config
297
)
298
```
299
300
### System Information
301
302
```python
303
client = docker.from_env()
304
305
# System info
306
info = client.info()
307
print(f"Docker version: {info['ServerVersion']}")
308
print(f"Storage driver: {info['Driver']}")
309
310
# Disk usage
311
usage = client.df()
312
print(f"Images: {len(usage['Images'])} using {usage['LayersSize']} bytes")
313
314
# Version details
315
version = client.version()
316
print(f"API version: {version['ApiVersion']}")
317
```
318
319
### Event Monitoring
320
321
```python
322
import docker
323
from datetime import datetime, timedelta
324
325
client = docker.from_env()
326
327
# Monitor all events
328
for event in client.events(decode=True):
329
print(f"{event['time']}: {event['Action']} on {event['Type']}")
330
331
# Filter events
332
filters = {'type': 'container', 'event': ['start', 'stop']}
333
since = datetime.now() - timedelta(hours=1)
334
335
for event in client.events(since=since, filters=filters, decode=True):
336
container_name = event['Actor']['Attributes'].get('name', 'unknown')
337
print(f"Container {container_name}: {event['Action']}")
338
```