0
# Client Configuration
1
2
Main Docker client interface and configuration options for connecting to different Docker daemons, setting up contexts, and managing authentication. The DockerClient serves as the primary entry point for all Docker operations.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Create and configure Docker client instances with various connection options.
9
10
```python { .api }
11
class DockerClient:
12
def __init__(
13
self,
14
*,
15
config: Optional[str] = None,
16
context: Optional[str] = None,
17
debug: bool = False,
18
host: Optional[str] = None,
19
log_level: str = "info",
20
tls: bool = False,
21
tlscacert: Optional[str] = None,
22
tlscert: Optional[str] = None,
23
tlskey: Optional[str] = None,
24
tlsverify: bool = False,
25
compose_files: Optional[List[str]] = None,
26
compose_profiles: Optional[List[str]] = None,
27
compose_env_file: Optional[str] = None,
28
compose_project_name: Optional[str] = None,
29
compose_project_directory: Optional[str] = None,
30
compose_compatibility: bool = False,
31
client_call: Optional[List[str]] = None,
32
client_type: str = "docker"
33
):
34
"""
35
Initialize Docker client.
36
37
Parameters:
38
- config: Location of client config files (default "~/.docker")
39
- context: Name of the context to use for daemon connection
40
- debug: Enable debug mode
41
- host: Daemon socket(s) to connect to
42
- log_level: Logging level (debug, info, warn, error, fatal)
43
- tls: Use TLS; implied by tlsverify
44
- tlscacert: Trust certs signed only by this CA
45
- tlscert: Path to TLS certificate file
46
- tlskey: Path to TLS key file
47
- tlsverify: Use TLS and verify the remote
48
- compose_files: Docker compose yaml file(s)
49
- compose_profiles: List of compose profiles to use
50
- compose_env_file: .env file for compose environment variables
51
- compose_project_name: Name of the compose project
52
- compose_project_directory: Working directory for compose
53
- compose_compatibility: Use docker compose in compatibility mode
54
- client_call: Client binary and arguments to use
55
- client_type: Type of client (docker, podman)
56
"""
57
```
58
59
### Version Information
60
61
Retrieve Docker client and server version information.
62
63
```python { .api }
64
def version() -> Version:
65
"""
66
Get Docker version information.
67
68
Returns:
69
- Version object with client and server details
70
"""
71
```
72
73
### Authentication
74
75
Manage registry authentication and login credentials.
76
77
```python { .api }
78
def login(
79
server: Optional[str] = None,
80
*,
81
username: Optional[str] = None,
82
password: Optional[str] = None,
83
password_stdin: bool = False
84
) -> None:
85
"""
86
Log in to Docker registry.
87
88
Parameters:
89
- server: Server URL (defaults to Docker Hub)
90
- username: Username for authentication
91
- password: Password for authentication
92
- password_stdin: Read password from stdin
93
"""
94
95
def logout(server: Optional[str] = None) -> None:
96
"""
97
Log out from Docker registry.
98
99
Parameters:
100
- server: Server URL (defaults to Docker Hub)
101
"""
102
103
def login_ecr(
104
region: str,
105
*,
106
profile: Optional[str] = None,
107
access_key_id: Optional[str] = None,
108
secret_access_key: Optional[str] = None,
109
session_token: Optional[str] = None
110
) -> None:
111
"""
112
Log in to Amazon ECR.
113
114
Parameters:
115
- region: AWS region
116
- profile: AWS profile to use
117
- access_key_id: AWS access key ID
118
- secret_access_key: AWS secret access key
119
- session_token: AWS session token
120
"""
121
```
122
123
## Usage Examples
124
125
### Basic Client Setup
126
127
```python
128
from python_on_whales import DockerClient
129
130
# Use default Docker daemon
131
docker = DockerClient()
132
133
# Connect to remote Docker daemon
134
remote_docker = DockerClient(host="tcp://192.168.1.100:2376")
135
136
# Use specific context
137
context_docker = DockerClient(context="production")
138
139
# Enable debug logging
140
debug_docker = DockerClient(debug=True, log_level="debug")
141
```
142
143
### TLS Configuration
144
145
```python
146
# TLS with certificate verification
147
secure_docker = DockerClient(
148
host="tcp://docker.example.com:2376",
149
tls=True,
150
tlsverify=True,
151
tlscacert="/path/to/ca.pem",
152
tlscert="/path/to/cert.pem",
153
tlskey="/path/to/key.pem"
154
)
155
156
# Simple TLS without verification
157
simple_tls_docker = DockerClient(
158
host="tcp://docker.example.com:2376",
159
tls=True
160
)
161
```
162
163
### Alternative Client Binaries
164
165
```python
166
# Use Podman instead of Docker
167
podman = DockerClient(
168
client_call=["podman"],
169
client_type="podman"
170
)
171
172
# Use Docker with sudo
173
sudo_docker = DockerClient(
174
client_call=["sudo", "docker"]
175
)
176
177
# Use nerdctl with custom options
178
nerdctl = DockerClient(
179
client_call=["nerdctl", "--snapshotter=stargz"],
180
client_type="docker"
181
)
182
183
# SSH to remote Docker
184
ssh_docker = DockerClient(
185
host="ssh://user@remote-host"
186
)
187
```
188
189
### Compose Integration
190
191
```python
192
# Client with Compose configuration
193
compose_docker = DockerClient(
194
compose_files=["docker-compose.yml", "docker-compose.prod.yml"],
195
compose_project_name="myapp",
196
compose_profiles=["web", "db"],
197
compose_env_file=".env.production"
198
)
199
200
# Use the compose functionality
201
compose_docker.compose.up(detach=True)
202
```
203
204
### Version and Authentication
205
206
```python
207
# Check version compatibility
208
version_info = docker.version()
209
print(f"Client Version: {version_info.client.version}")
210
print(f"Server Version: {version_info.server.version}")
211
print(f"API Version: {version_info.client.api_version}")
212
213
# Authenticate with registry
214
docker.login("registry.example.com", username="myuser", password="mypass")
215
216
# Authenticate with AWS ECR
217
docker.login_ecr("us-west-2", profile="production")
218
219
# Logout
220
docker.logout("registry.example.com")
221
```
222
223
### Global Docker Instance
224
225
```python
226
# Use the pre-configured global instance
227
from python_on_whales import docker
228
229
# This is equivalent to DockerClient()
230
containers = docker.ps()
231
images = docker.images()
232
233
# All methods available on the global instance
234
result = docker.run("hello-world")
235
```
236
237
### Configuration Validation
238
239
```python
240
def validate_docker_config(client: DockerClient) -> bool:
241
"""Validate Docker client configuration."""
242
try:
243
# Test basic connectivity
244
version = client.version()
245
print(f"✓ Connected to Docker {version.server.version}")
246
247
# Test basic operations
248
client.ps()
249
print("✓ Container operations available")
250
251
client.images()
252
print("✓ Image operations available")
253
254
return True
255
256
except Exception as e:
257
print(f"✗ Docker configuration error: {e}")
258
return False
259
260
# Test different configurations
261
configs = [
262
DockerClient(), # Default
263
DockerClient(host="unix:///var/run/docker.sock"), # Unix socket
264
DockerClient(context="default"), # Named context
265
]
266
267
for i, config in enumerate(configs):
268
print(f"Testing configuration {i+1}:")
269
if validate_docker_config(config):
270
print("Configuration is valid\n")
271
else:
272
print("Configuration failed\n")
273
```
274
275
## Types
276
277
```python { .api }
278
class DockerClient:
279
# Component access properties
280
buildx: BuildxCLI
281
compose: ComposeCLI
282
config: ConfigCLI
283
container: ContainerCLI
284
context: ContextCLI
285
image: ImageCLI
286
manifest: ManifestCLI
287
network: NetworkCLI
288
node: NodeCLI
289
plugin: PluginCLI
290
pod: PodCLI
291
secret: SecretCLI
292
service: ServiceCLI
293
stack: StackCLI
294
swarm: SwarmCLI
295
system: SystemCLI
296
task: TaskCLI
297
trust: TrustCLI
298
volume: VolumeCLI
299
300
# Direct method aliases
301
def attach(self, container: str, **kwargs) -> None: ...
302
def build(self, context_path: str, **kwargs) -> Image: ...
303
def commit(self, container: str, **kwargs) -> Image: ...
304
def copy(self, source: str, destination: str, **kwargs) -> None: ...
305
def create(self, image: str, **kwargs) -> Container: ...
306
def execute(self, container: str, command: List[str], **kwargs) -> str: ...
307
def export(self, container: str, output_path: str) -> None: ...
308
def images(self, **kwargs) -> List[Image]: ...
309
def import_(self, source: str, **kwargs) -> Image: ...
310
def info(self) -> SystemInfo: ...
311
def kill(self, containers: Union[str, List[str]], **kwargs) -> None: ...
312
def load(self, input_path: str, **kwargs) -> List[str]: ...
313
def logs(self, container: str, **kwargs) -> str: ...
314
def pause(self, containers: Union[str, List[str]]) -> None: ...
315
def ps(self, **kwargs) -> List[Container]: ...
316
def pull(self, image_name: str, **kwargs) -> Image: ...
317
def push(self, image_name: str, **kwargs) -> str: ...
318
def rename(self, container: str, new_name: str) -> None: ...
319
def restart(self, containers: Union[str, List[str]], **kwargs) -> None: ...
320
def remove(self, containers: Union[str, List[str]], **kwargs) -> None: ...
321
def run(self, image: str, **kwargs) -> Union[str, Container]: ...
322
def save(self, images: Union[str, List[str]], output_path: str) -> None: ...
323
def start(self, containers: Union[str, List[str]]) -> None: ...
324
def stats(self, **kwargs) -> Union[List[ContainerStats], Iterator[List[ContainerStats]]]: ...
325
def stop(self, containers: Union[str, List[str]], **kwargs) -> None: ...
326
def tag(self, source_image: str, target_repository: str, target_tag: Optional[str] = None) -> None: ...
327
def top(self, container: str, **kwargs) -> List[Dict[str, str]]: ...
328
def unpause(self, containers: Union[str, List[str]]) -> None: ...
329
def update(self, containers: Union[str, List[str]], **kwargs) -> None: ...
330
def wait(self, containers: Union[str, List[str]], **kwargs) -> List[Dict[str, Any]]: ...
331
332
class Version:
333
client: Optional[ClientVersion]
334
server: Optional[ServerVersion]
335
336
class ClientVersion:
337
platform: Optional[Dict[str, str]]
338
version: Optional[str]
339
api_version: Optional[str]
340
default_api_version: Optional[str]
341
git_commit: Optional[str]
342
go_version: Optional[str]
343
os: Optional[str]
344
arch: Optional[str]
345
build_time: Optional[str]
346
context: Optional[str]
347
experimental: Optional[bool]
348
349
class ServerVersion:
350
platform: Optional[Dict[str, str]]
351
components: Optional[List[ServerVersionComponent]]
352
version: Optional[str]
353
api_version: Optional[str]
354
min_api_version: Optional[str]
355
git_commit: Optional[str]
356
go_version: Optional[str]
357
os: Optional[str]
358
arch: Optional[str]
359
kernel_version: Optional[str]
360
build_time: Optional[str]
361
362
class ServerVersionComponent:
363
name: Optional[str]
364
version: Optional[str]
365
details: Optional[Dict[str, str]]
366
```