0
# Container Management
1
2
Complete container lifecycle management including creation, execution, monitoring, and resource control with support for advanced features like container attachment, file transfer, and process execution.
3
4
## Capabilities
5
6
### ContainerCollection
7
8
High-level container management operations accessible via `client.containers`.
9
10
```python { .api }
11
class ContainerCollection:
12
def run(self, image, command=None, **kwargs):
13
"""
14
Create and start a container.
15
16
Args:
17
image (str): Image name or ID to run
18
command (str or list): Command to execute in container
19
**kwargs: Container configuration options
20
21
Returns:
22
Container: Running container instance
23
24
Common kwargs:
25
auto_remove (bool): Remove container when it exits
26
detach (bool): Run in background (default: False)
27
environment (dict or list): Environment variables
28
name (str): Container name
29
ports (dict): Port mappings {'container_port': host_port}
30
volumes (dict): Volume mounts {'host_path': {'bind': '/container/path', 'mode': 'rw'}}
31
working_dir (str): Working directory inside container
32
user (str): User to run as
33
network (str): Network to connect to
34
restart_policy (dict): Restart policy configuration
35
"""
36
37
def create(self, image, command=None, **kwargs):
38
"""
39
Create a container without starting it.
40
41
Args:
42
image (str): Image name or ID
43
command (str or list): Command to execute
44
**kwargs: Same as run() method
45
46
Returns:
47
Container: Container instance (not started)
48
"""
49
50
def get(self, container_id):
51
"""
52
Get a container by ID or name.
53
54
Args:
55
container_id (str): Container ID or name
56
57
Returns:
58
Container: Container instance
59
60
Raises:
61
NotFound: If container doesn't exist
62
"""
63
64
def list(self, all=False, before=None, filters=None, limit=None, since=None, sparse=False):
65
"""
66
List containers.
67
68
Args:
69
all (bool): Include stopped containers
70
before (str): Show containers created before this container ID
71
filters (dict): Filter results by status, label, etc.
72
limit (int): Maximum number of containers to return
73
since (str): Show containers created since this container ID
74
sparse (bool): Return limited information
75
76
Returns:
77
list[Container]: List of container instances
78
"""
79
80
def prune(self, filters=None):
81
"""
82
Remove unused containers.
83
84
Args:
85
filters (dict): Filters to apply when pruning
86
87
Returns:
88
dict: Pruning results with space reclaimed
89
"""
90
```
91
92
### Container Model
93
94
Individual container instance with lifecycle and operational methods.
95
96
```python { .api }
97
class Container:
98
"""
99
A Docker container instance.
100
101
Properties:
102
id (str): Full container ID
103
short_id (str): Short container ID (12 characters)
104
name (str): Container name
105
image (Image): Container image object
106
labels (dict): Container labels
107
status (str): Container status ('running', 'exited', 'paused', etc.)
108
health (str): Healthcheck status ('healthy', 'unhealthy', 'starting', 'unknown')
109
ports (dict): Exposed port mappings
110
attrs (dict): Raw container attributes from Docker API
111
"""
112
```
113
114
#### Lifecycle Operations
115
116
```python { .api }
117
def start(self, **kwargs):
118
"""
119
Start the container.
120
121
Raises:
122
APIError: If container cannot be started
123
"""
124
125
def stop(self, timeout=10):
126
"""
127
Stop the container gracefully.
128
129
Args:
130
timeout (int): Seconds to wait before killing container
131
"""
132
133
def restart(self, timeout=10):
134
"""
135
Restart the container.
136
137
Args:
138
timeout (int): Seconds to wait before killing during restart
139
"""
140
141
def kill(self, signal='SIGKILL'):
142
"""
143
Kill the container with a signal.
144
145
Args:
146
signal (str or int): Signal to send (default: SIGKILL)
147
"""
148
149
def pause(self):
150
"""Pause all processes in the container."""
151
152
def unpause(self):
153
"""Unpause all processes in the container."""
154
155
def remove(self, v=False, link=False, force=False):
156
"""
157
Remove the container.
158
159
Args:
160
v (bool): Remove associated anonymous volumes
161
link (bool): Remove specified link
162
force (bool): Force removal of running container
163
"""
164
165
def wait(self, timeout=None, condition='not-running'):
166
"""
167
Wait for container to stop.
168
169
Args:
170
timeout (int): Timeout in seconds
171
condition (str): Condition to wait for ('not-running', 'next-exit', 'removed')
172
173
Returns:
174
dict: Exit status and error information
175
"""
176
```
177
178
#### Process Execution
179
180
```python { .api }
181
def exec_run(self, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', environment=None, workdir=None, detach=False, stream=False, socket=False, demux=False):
182
"""
183
Execute a command inside the container.
184
185
Args:
186
cmd (str or list): Command to execute
187
stdout (bool): Capture stdout
188
stderr (bool): Capture stderr
189
stdin (bool): Enable stdin
190
tty (bool): Allocate pseudo-TTY
191
privileged (bool): Run with extended privileges
192
user (str): User to run command as
193
environment (list): Environment variables ['VAR=value']
194
workdir (str): Working directory for command
195
detach (bool): Run in background
196
stream (bool): Stream output
197
socket (bool): Return socket instead of output
198
demux (bool): Separate stdout/stderr streams
199
200
Returns:
201
ExecResult: Named tuple with (exit_code, output) or generator if stream=True
202
"""
203
204
def top(self, ps_args=None):
205
"""
206
Get running processes in container.
207
208
Args:
209
ps_args (str): Arguments to ps command
210
211
Returns:
212
dict: Process information with titles and processes
213
"""
214
```
215
216
#### Monitoring and Logging
217
218
```python { .api }
219
def logs(self, stdout=True, stderr=True, stream=False, timestamps=False, tail='all', since=None, follow=None, until=None):
220
"""
221
Get container logs.
222
223
Args:
224
stdout (bool): Include stdout
225
stderr (bool): Include stderr
226
stream (bool): Stream logs continuously
227
timestamps (bool): Include timestamps
228
tail (str or int): Number of lines from end ('all' for all)
229
since (datetime or str): Show logs since timestamp
230
follow (bool): Follow log output (same as stream)
231
until (datetime or str): Show logs until timestamp
232
233
Returns:
234
bytes or generator: Log output or log stream if stream=True
235
"""
236
237
def stats(self, decode=None, stream=True):
238
"""
239
Get container resource usage statistics.
240
241
Args:
242
decode (bool): Decode JSON statistics
243
stream (bool): Stream statistics continuously
244
245
Returns:
246
dict or generator: Resource usage statistics
247
"""
248
249
def attach(self, **kwargs):
250
"""
251
Attach to container's stdin/stdout/stderr.
252
253
Args:
254
stdout (bool): Attach to stdout (default: True)
255
stderr (bool): Attach to stderr (default: True)
256
stream (bool): Stream output (default: True)
257
logs (bool): Include previous output (default: False)
258
259
Returns:
260
generator: Output stream
261
"""
262
263
def attach_socket(self, **kwargs):
264
"""
265
Get a socket for container attachment.
266
267
Args:
268
params (dict): Attachment parameters
269
ws (bool): Use WebSocket for attachment
270
271
Returns:
272
socket: Raw socket for attachment
273
"""
274
```
275
276
#### File Operations
277
278
```python { .api }
279
def diff(self):
280
"""
281
Inspect changes on container's filesystem since creation.
282
283
Returns:
284
list: List of dictionaries containing 'Path' and 'Kind' attributes
285
Kind values: 0=Modified, 1=Added, 2=Deleted
286
"""
287
288
def put_archive(self, path, data):
289
"""
290
Upload tar archive to container filesystem.
291
292
Args:
293
path (str): Destination path in container
294
data (bytes): Tar archive data
295
296
Returns:
297
bool: True if successful
298
"""
299
300
def get_archive(self, path, chunk_size=2097152):
301
"""
302
Download tar archive from container filesystem.
303
304
Args:
305
path (str): Source path in container
306
chunk_size (int): Chunk size for streaming
307
308
Returns:
309
tuple: (tar_stream, stat_info)
310
311
Raises:
312
NotFound: If path doesn't exist
313
"""
314
315
def export(self, chunk_size=2097152):
316
"""
317
Export container filesystem as tar archive.
318
319
Args:
320
chunk_size (int): Chunk size for streaming
321
322
Returns:
323
generator: Tar archive data chunks
324
"""
325
```
326
327
#### Container Updates
328
329
```python { .api }
330
def update(self, **kwargs):
331
"""
332
Update container resource configuration.
333
334
Args:
335
**kwargs: Resource constraints to update
336
337
Common kwargs:
338
mem_limit (str or int): Memory limit
339
memswap_limit (str or int): Memory + swap limit
340
cpu_shares (int): CPU shares (relative weight)
341
cpu_period (int): CPU CFS period
342
cpu_quota (int): CPU CFS quota
343
cpuset_cpus (str): CPUs to use (0-3, 0,1)
344
cpuset_mems (str): Memory nodes to use
345
restart_policy (dict): Restart policy
346
"""
347
348
def commit(self, repository=None, tag=None, message=None, author=None, changes=None, conf=None):
349
"""
350
Create new image from container changes.
351
352
Args:
353
repository (str): Repository name for new image
354
tag (str): Tag for new image
355
message (str): Commit message
356
author (str): Author information
357
changes (list): Dockerfile instructions to apply
358
conf (dict): Container configuration changes
359
360
Returns:
361
Image: New image created from container
362
"""
363
364
def rename(self, name):
365
"""
366
Rename the container.
367
368
Args:
369
name (str): New container name
370
"""
371
372
def resize(self, height, width):
373
"""
374
Resize container TTY.
375
376
Args:
377
height (int): TTY height
378
width (int): TTY width
379
"""
380
```
381
382
## Usage Examples
383
384
### Basic Container Operations
385
386
```python
387
import docker
388
389
client = docker.from_env()
390
391
# Run a simple container
392
container = client.containers.run(
393
'ubuntu:20.04',
394
'echo "Hello World"',
395
remove=True
396
)
397
398
# Run detached container with port mapping
399
web_container = client.containers.run(
400
'nginx:latest',
401
detach=True,
402
ports={'80/tcp': 8080},
403
name='my-nginx'
404
)
405
406
# Get container and check status
407
container = client.containers.get('my-nginx')
408
print(f"Status: {container.status}")
409
410
# Stop and remove
411
container.stop()
412
container.remove()
413
```
414
415
### Advanced Container Configuration
416
417
```python
418
# Run with volumes, environment variables, and resource limits
419
container = client.containers.run(
420
'python:3.9',
421
'python /app/main.py',
422
detach=True,
423
environment={
424
'DATABASE_URL': 'postgresql://localhost/mydb',
425
'DEBUG': 'true'
426
},
427
volumes={
428
'/host/app': {'bind': '/app', 'mode': 'ro'},
429
'/host/data': {'bind': '/data', 'mode': 'rw'}
430
},
431
ports={'5000/tcp': 5000},
432
mem_limit='512m',
433
cpu_shares=512,
434
restart_policy={'Name': 'unless-stopped'},
435
name='my-python-app'
436
)
437
```
438
439
### Process Execution and Monitoring
440
441
```python
442
container = client.containers.get('my-app')
443
444
# Execute command in running container
445
result = container.exec_run('ls -la /app')
446
print(f"Exit code: {result.exit_code}")
447
print(f"Output: {result.output.decode()}")
448
449
# Interactive execution with TTY
450
exec_result = container.exec_run(
451
'bash',
452
stdin=True,
453
tty=True,
454
socket=True
455
)
456
457
# Get running processes
458
processes = container.top()
459
for process in processes['Processes']:
460
print(f"PID: {process[1]}, Command: {process[7]}")
461
462
# Stream logs
463
for line in container.logs(stream=True, follow=True):
464
print(line.decode().strip())
465
466
# Monitor resource usage
467
for stats in container.stats(decode=True):
468
cpu_percent = stats['cpu_stats']['cpu_usage']['total_usage']
469
memory_usage = stats['memory_stats']['usage']
470
print(f"CPU: {cpu_percent}, Memory: {memory_usage}")
471
```
472
473
### File Operations
474
475
```python
476
import tarfile
477
import io
478
479
container = client.containers.get('my-app')
480
481
# Upload file to container
482
tar_data = io.BytesIO()
483
with tarfile.open(fileobj=tar_data, mode='w') as tar:
484
tar.add('/local/config.json', arcname='config.json')
485
486
tar_data.seek(0)
487
container.put_archive('/app/', tar_data.getvalue())
488
489
# Download file from container
490
archive, stats = container.get_archive('/app/output.log')
491
with open('/local/output.log', 'wb') as f:
492
for chunk in archive:
493
f.write(chunk)
494
495
# Export entire container filesystem
496
with open('/local/container_export.tar', 'wb') as f:
497
for chunk in container.export():
498
f.write(chunk)
499
```
500
501
### Container Lifecycle Management
502
503
```python
504
# Create container without starting
505
container = client.containers.create(
506
'redis:alpine',
507
name='my-redis',
508
ports={'6379/tcp': 6379}
509
)
510
511
# Start when ready
512
container.start()
513
514
# Pause/unpause operations
515
container.pause()
516
print(f"Status: {container.status}") # paused
517
518
container.unpause()
519
print(f"Status: {container.status}") # running
520
521
# Graceful shutdown with timeout
522
container.stop(timeout=30)
523
524
# Wait for container to exit
525
result = container.wait()
526
print(f"Exit code: {result['StatusCode']}")
527
528
# Force removal
529
container.remove(force=True)
530
```