0
# Container Operations
1
2
Complete container lifecycle management providing programmatic control over Docker containers. Covers creation, startup, monitoring, resource management, and cleanup operations with support for advanced features like networking, volume mounts, and process execution.
3
4
## Capabilities
5
6
### Container Lifecycle Management
7
8
Core container operations for creating, starting, stopping, and removing containers with comprehensive configuration options.
9
10
```python { .api }
11
def create_container(image, command=None, hostname=None, user=None,
12
detach=False, stdin_open=False, tty=False,
13
mem_limit=None, ports=None, environment=None,
14
dns=None, volumes=None, volumes_from=None,
15
network_disabled=False, name=None, entrypoint=None,
16
cpu_shares=None, working_dir=None, domainname=None,
17
memswap_limit=None, cpuset=None, host_config=None,
18
mac_address=None, labels=None, volume_driver=None,
19
stop_signal=None, networking_config=None):
20
"""
21
Create a new container.
22
23
Parameters:
24
- image (str): Image name to create container from
25
- command (str|list): Command to run in container
26
- hostname (str): Container hostname
27
- user (str): Username or UID to run commands as
28
- detach (bool): Run container in detached mode
29
- stdin_open (bool): Keep STDIN open
30
- tty (bool): Allocate a pseudo-TTY
31
- mem_limit (int|str): Memory limit
32
- ports (list): Ports to expose
33
- environment (dict|list): Environment variables
34
- dns (list): DNS servers
35
- volumes (list): Volume mount points
36
- volumes_from (list): Mount volumes from other containers
37
- network_disabled (bool): Disable networking
38
- name (str): Container name
39
- entrypoint (str|list): Override default entrypoint
40
- cpu_shares (int): CPU shares weight
41
- working_dir (str): Working directory
42
- domainname (str): Container domain name
43
- memswap_limit (int): Memory + swap limit
44
- cpuset (str): CPUs to use
45
- host_config (dict): Host configuration
46
- mac_address (str): Container MAC address
47
- labels (dict): Container labels
48
- volume_driver (str): Volume driver name
49
- stop_signal (str): Signal to stop container
50
- networking_config (dict): Network configuration
51
52
Returns:
53
dict: Container creation response with 'Id' key
54
"""
55
56
def start(container, binds=None, port_bindings=None, lxc_conf=None,
57
publish_all_ports=None, links=None, privileged=None,
58
dns=None, dns_search=None, volumes_from=None,
59
network_mode=None, restart_policy=None, cap_add=None,
60
cap_drop=None, devices=None, extra_hosts=None,
61
read_only=None, pid_mode=None, ipc_mode=None,
62
security_opt=None, ulimits=None):
63
"""
64
Start a container.
65
66
Parameters:
67
- container (str): Container ID or name
68
- binds (dict): Volume bindings
69
- port_bindings (dict): Port bindings
70
- lxc_conf (dict): LXC configuration
71
- publish_all_ports (bool): Publish all exposed ports
72
- links (list): Container links
73
- privileged (bool): Run in privileged mode
74
- dns (list): DNS servers
75
- dns_search (list): DNS search domains
76
- volumes_from (list): Mount volumes from containers
77
- network_mode (str): Network mode
78
- restart_policy (dict): Restart policy configuration
79
- cap_add (list): Linux capabilities to add
80
- cap_drop (list): Linux capabilities to drop
81
- devices (list): Device mappings
82
- extra_hosts (list): Extra host entries
83
- read_only (bool): Mount root filesystem as read-only
84
- pid_mode (str): PID namespace mode
85
- ipc_mode (str): IPC namespace mode
86
- security_opt (list): Security options
87
- ulimits (list): Resource limits
88
89
Returns:
90
None
91
"""
92
93
def stop(container, timeout=10):
94
"""
95
Stop a running container.
96
97
Parameters:
98
- container (str): Container ID or name
99
- timeout (int): Seconds to wait before killing
100
101
Returns:
102
None
103
"""
104
105
def restart(container, timeout=10):
106
"""
107
Restart a container.
108
109
Parameters:
110
- container (str): Container ID or name
111
- timeout (int): Seconds to wait before killing
112
113
Returns:
114
None
115
"""
116
117
def kill(container, signal=None):
118
"""
119
Kill a running container.
120
121
Parameters:
122
- container (str): Container ID or name
123
- signal (str): Signal to send (default: SIGKILL)
124
125
Returns:
126
None
127
"""
128
129
def pause(container):
130
"""
131
Pause all processes in a container.
132
133
Parameters:
134
- container (str): Container ID or name
135
136
Returns:
137
None
138
"""
139
140
def unpause(container):
141
"""
142
Unpause all processes in a container.
143
144
Parameters:
145
- container (str): Container ID or name
146
147
Returns:
148
None
149
"""
150
151
def remove_container(container, v=False, link=False, force=False):
152
"""
153
Remove a container.
154
155
Parameters:
156
- container (str): Container ID or name
157
- v (bool): Remove associated volumes
158
- link (bool): Remove specified link
159
- force (bool): Force removal of running container
160
161
Returns:
162
None
163
"""
164
165
def rename(container, name):
166
"""
167
Rename a container.
168
169
Parameters:
170
- container (str): Container ID or name
171
- name (str): New container name
172
173
Returns:
174
None
175
"""
176
```
177
178
### Container Inspection and Monitoring
179
180
Functions to retrieve container information, status, and resource usage statistics.
181
182
```python { .api }
183
def containers(quiet=False, all=False, trunc=False, latest=False,
184
since=None, before=None, limit=-1, size=False, filters=None):
185
"""
186
List containers.
187
188
Parameters:
189
- quiet (bool): Only return container IDs
190
- all (bool): Show all containers (default: running only)
191
- trunc (bool): Truncate output
192
- latest (bool): Show only latest created container
193
- since (str): Show containers created since container ID
194
- before (str): Show containers created before container ID
195
- limit (int): Show 'limit' last created containers
196
- size (bool): Display total file sizes
197
- filters (dict): Filters to process on container list
198
199
Returns:
200
list: List of container dictionaries
201
"""
202
203
def inspect_container(container):
204
"""
205
Get detailed information about a container.
206
207
Parameters:
208
- container (str): Container ID or name
209
210
Returns:
211
dict: Container configuration and state information
212
"""
213
214
def logs(container, stdout=True, stderr=True, stream=False,
215
timestamps=False, tail='all', since=None, follow=None):
216
"""
217
Get container logs.
218
219
Parameters:
220
- container (str): Container ID or name
221
- stdout (bool): Include stdout
222
- stderr (bool): Include stderr
223
- stream (bool): Stream logs as generator
224
- timestamps (bool): Show timestamps
225
- tail (str|int): Number of lines from end ('all' for all)
226
- since (int): Show logs since timestamp
227
- follow (bool): Follow log output (stream must be True)
228
229
Returns:
230
bytes|generator: Log data or generator if stream=True
231
"""
232
233
def stats(container, decode=None, stream=True):
234
"""
235
Get container resource usage statistics.
236
237
Parameters:
238
- container (str): Container ID or name
239
- decode (bool): Decode JSON statistics
240
- stream (bool): Stream statistics as generator
241
242
Returns:
243
dict|generator: Statistics data or generator if stream=True
244
"""
245
246
def top(container, ps_args=None):
247
"""
248
Get running processes in a container.
249
250
Parameters:
251
- container (str): Container ID or name
252
- ps_args (str): ps command arguments
253
254
Returns:
255
dict: Process list with 'Titles' and 'Processes' keys
256
"""
257
258
def diff(container):
259
"""
260
Get changes to container's filesystem.
261
262
Parameters:
263
- container (str): Container ID or name
264
265
Returns:
266
list: List of filesystem changes
267
"""
268
269
def port(container, private_port):
270
"""
271
Get port mapping for a container port.
272
273
Parameters:
274
- container (str): Container ID or name
275
- private_port (int): Private port number
276
277
Returns:
278
list: Port binding information
279
"""
280
```
281
282
### Container Process Execution
283
284
Execute commands within running containers with full control over environment and I/O.
285
286
```python { .api }
287
def exec_create(container, cmd, stdout=True, stderr=True,
288
stdin=False, tty=False, privileged=False, user=''):
289
"""
290
Create an exec instance for running commands in a container.
291
292
Parameters:
293
- container (str): Container ID or name
294
- cmd (str|list): Command to execute
295
- stdout (bool): Attach to stdout
296
- stderr (bool): Attach to stderr
297
- stdin (bool): Attach to stdin
298
- tty (bool): Allocate pseudo-TTY
299
- privileged (bool): Run in privileged mode
300
- user (str): User to run command as
301
302
Returns:
303
dict: Exec instance information with 'Id' key
304
"""
305
306
def exec_start(exec_id, detach=False, tty=False, stream=False, socket=False):
307
"""
308
Start an exec instance.
309
310
Parameters:
311
- exec_id (str): Exec instance ID
312
- detach (bool): Detach from exec
313
- tty (bool): Allocate pseudo-TTY
314
- stream (bool): Stream output
315
- socket (bool): Return socket instead of output
316
317
Returns:
318
bytes|generator|socket: Command output or generator/socket
319
"""
320
321
def exec_inspect(exec_id):
322
"""
323
Get detailed information about an exec instance.
324
325
Parameters:
326
- exec_id (str): Exec instance ID
327
328
Returns:
329
dict: Exec instance details and state
330
"""
331
332
def exec_resize(exec_id, height=None, width=None):
333
"""
334
Resize the TTY of an exec instance.
335
336
Parameters:
337
- exec_id (str): Exec instance ID
338
- height (int): TTY height
339
- width (int): TTY width
340
341
Returns:
342
None
343
"""
344
```
345
346
### Container Data Operations
347
348
File and data transfer operations between containers and the host system.
349
350
```python { .api }
351
def attach(container, stdout=True, stderr=True, stream=False, logs=False):
352
"""
353
Attach to a container's I/O streams.
354
355
Parameters:
356
- container (str): Container ID or name
357
- stdout (bool): Attach to stdout
358
- stderr (bool): Attach to stderr
359
- stream (bool): Stream output
360
- logs (bool): Include logs in output
361
362
Returns:
363
bytes|generator: Output data or generator if stream=True
364
"""
365
366
def attach_socket(container, params=None, ws=False):
367
"""
368
Get a socket to attach to container streams.
369
370
Parameters:
371
- container (str): Container ID or name
372
- params (dict): Additional parameters
373
- ws (bool): Use WebSocket connection
374
375
Returns:
376
socket: Socket for container attachment
377
"""
378
379
def get_archive(container, path):
380
"""
381
Get a tar archive of files from container path.
382
383
Parameters:
384
- container (str): Container ID or name
385
- path (str): Path in container to retrieve
386
387
Returns:
388
tuple: (tar_data, stat_info) where tar_data is bytes
389
"""
390
391
def put_archive(container, path, data):
392
"""
393
Put a tar archive into container at specified path.
394
395
Parameters:
396
- container (str): Container ID or name
397
- path (str): Path in container to extract to
398
- data (bytes): Tar archive data
399
400
Returns:
401
bool: Success status
402
"""
403
404
def copy(container, resource):
405
"""
406
Copy files from a container (deprecated for API >= 1.20).
407
408
Parameters:
409
- container (str): Container ID or name
410
- resource (str): Path to copy from container
411
412
Returns:
413
bytes: File data
414
"""
415
416
def export(container):
417
"""
418
Export container filesystem as tar archive.
419
420
Parameters:
421
- container (str): Container ID or name
422
423
Returns:
424
generator: Tar archive data stream
425
"""
426
427
def commit(container, repository=None, tag=None, message=None,
428
author=None, changes=None, conf=None):
429
"""
430
Create a new image from container changes.
431
432
Parameters:
433
- container (str): Container ID or name
434
- repository (str): Repository name for new image
435
- tag (str): Tag for new image
436
- message (str): Commit message
437
- author (str): Author of commit
438
- changes (list): Dockerfile-like changes
439
- conf (dict): Container configuration
440
441
Returns:
442
str: New image ID
443
"""
444
445
def wait(container, timeout=None):
446
"""
447
Wait for a container to stop and return its exit code.
448
449
Parameters:
450
- container (str): Container ID or name
451
- timeout (int): Timeout in seconds
452
453
Returns:
454
dict: Exit code information
455
"""
456
457
def resize(container, height, width):
458
"""
459
Resize a container's TTY.
460
461
Parameters:
462
- container (str): Container ID or name
463
- height (int): TTY height
464
- width (int): TTY width
465
466
Returns:
467
None
468
"""
469
```
470
471
### Container Resource Management
472
473
Update and manage container resource constraints and configurations.
474
475
```python { .api }
476
def update_container(container, blkio_weight=None, cpu_period=None,
477
cpu_quota=None, cpu_shares=None, cpuset_cpus=None,
478
cpuset_mems=None, mem_limit=None, mem_reservation=None,
479
memswap_limit=None, kernel_memory=None):
480
"""
481
Update container resource constraints.
482
483
Parameters:
484
- container (str): Container ID or name
485
- blkio_weight (int): Block IO weight (10-1000)
486
- cpu_period (int): CPU CFS period
487
- cpu_quota (int): CPU CFS quota
488
- cpu_shares (int): CPU shares weight
489
- cpuset_cpus (str): CPUs to use
490
- cpuset_mems (str): Memory nodes to use
491
- mem_limit (int): Memory limit in bytes
492
- mem_reservation (int): Memory soft limit
493
- memswap_limit (int): Memory + swap limit
494
- kernel_memory (int): Kernel memory limit
495
496
Returns:
497
dict: Update response
498
"""
499
```
500
501
## Configuration Helper Functions
502
503
Functions for building complex container configurations with proper validation and formatting.
504
505
```python { .api }
506
def create_container_config(*args, **kwargs):
507
"""
508
Create a container configuration dictionary.
509
510
Returns:
511
dict: Container configuration
512
"""
513
514
def create_host_config(binds=None, port_bindings=None, lxc_conf=None,
515
publish_all_ports=False, links=None, privileged=False,
516
dns=None, dns_search=None, volumes_from=None,
517
network_mode=None, restart_policy=None, cap_add=None,
518
cap_drop=None, devices=None, extra_hosts=None,
519
read_only=None, pid_mode=None, ipc_mode=None,
520
security_opt=None, ulimits=None, log_config=None,
521
mem_limit=None, memswap_limit=None, mem_reservation=None,
522
kernel_memory=None, mem_swappiness=None,
523
cgroup_parent=None, group_add=None, cpu_quota=None,
524
cpu_period=None, blkio_weight=None,
525
blkio_weight_device=None, device_read_bps=None,
526
device_write_bps=None, device_read_iops=None,
527
device_write_iops=None, oom_kill_disable=None,
528
shm_size=None, sysctls=None, tmpfs=None,
529
oom_score_adj=None, dns_opt=None,
530
cpu_shares=None, cpuset_cpus=None, cpuset_mems=None,
531
userns_mode=None, pids_limit=None):
532
"""
533
Create host configuration for containers.
534
535
Parameters:
536
- binds (dict|list): Volume bindings
537
- port_bindings (dict): Port bindings
538
- lxc_conf (dict): LXC configuration
539
- publish_all_ports (bool): Publish all exposed ports
540
- links (list): Container links
541
- privileged (bool): Privileged mode
542
- dns (list): DNS servers
543
- dns_search (list): DNS search domains
544
- volumes_from (list): Mount volumes from containers
545
- network_mode (str): Network mode
546
- restart_policy (dict): Restart policy
547
- cap_add (list): Linux capabilities to add
548
- cap_drop (list): Linux capabilities to drop
549
- devices (list): Device mappings
550
- extra_hosts (list): Extra hosts entries
551
- read_only (bool): Read-only root filesystem
552
- pid_mode (str): PID namespace mode
553
- ipc_mode (str): IPC namespace mode
554
- security_opt (list): Security options
555
- ulimits (list): Resource limits
556
- log_config (LogConfig): Logging configuration
557
- mem_limit (int): Memory limit
558
- memswap_limit (int): Memory + swap limit
559
- mem_reservation (int): Memory soft limit
560
- kernel_memory (int): Kernel memory limit
561
- mem_swappiness (int): Memory swappiness (0-100)
562
- cgroup_parent (str): Parent cgroup
563
- group_add (list): Additional groups
564
- cpu_quota (int): CPU quota
565
- cpu_period (int): CPU period
566
- blkio_weight (int): Block IO weight
567
- blkio_weight_device (list): Block IO weight devices
568
- device_read_bps (list): Device read limits (bytes/sec)
569
- device_write_bps (list): Device write limits (bytes/sec)
570
- device_read_iops (list): Device read limits (operations/sec)
571
- device_write_iops (list): Device write limits (operations/sec)
572
- oom_kill_disable (bool): Disable OOM killer
573
- shm_size (int): Shared memory size
574
- sysctls (dict): Kernel parameters
575
- tmpfs (dict): Tmpfs mounts
576
- oom_score_adj (int): OOM score adjustment
577
- dns_opt (list): DNS options
578
- cpu_shares (int): CPU shares
579
- cpuset_cpus (str): CPUs to use
580
- cpuset_mems (str): Memory nodes to use
581
- userns_mode (str): User namespace mode
582
- pids_limit (int): PID limit
583
584
Returns:
585
dict: Host configuration
586
"""
587
588
def create_container_from_config(config, name=None):
589
"""
590
Create a container from a configuration dictionary.
591
592
Parameters:
593
- config (dict): Container configuration
594
- name (str): Container name
595
596
Returns:
597
dict: Container creation response
598
"""
599
```
600
601
## Usage Examples
602
603
### Basic Container Operations
604
605
```python
606
import docker
607
608
client = docker.Client()
609
610
# Create and run a simple container
611
container = client.create_container(
612
image='ubuntu:latest',
613
command='echo "Hello, Docker!"',
614
name='hello-container'
615
)
616
617
client.start(container)
618
client.wait(container)
619
620
# Get container output
621
logs = client.logs(container)
622
print(logs.decode('utf-8')) # "Hello, Docker!"
623
624
# Cleanup
625
client.remove_container(container)
626
```
627
628
### Interactive Container with TTY
629
630
```python
631
# Create interactive container
632
container = client.create_container(
633
image='ubuntu:latest',
634
command='/bin/bash',
635
tty=True,
636
stdin_open=True,
637
detach=True,
638
name='interactive-container'
639
)
640
641
client.start(container)
642
643
# Execute commands in the running container
644
exec_instance = client.exec_create(
645
container,
646
'ls -la /tmp',
647
stdout=True,
648
stderr=True
649
)
650
651
output = client.exec_start(exec_instance)
652
print(output.decode('utf-8'))
653
```
654
655
### Container with Custom Configuration
656
657
```python
658
# Create container with resource limits and volume mounts
659
host_config = client.create_host_config(
660
binds={'/host/path': {'bind': '/container/path', 'mode': 'rw'}},
661
port_bindings={'8080/tcp': 8080},
662
mem_limit='512m',
663
cpu_shares=512,
664
ulimits=[docker.types.Ulimit(name='nofile', soft=1024, hard=2048)]
665
)
666
667
container = client.create_container(
668
image='nginx:latest',
669
ports=['8080/tcp'],
670
volumes=['/container/path'],
671
host_config=host_config,
672
environment={'ENV_VAR': 'value'},
673
labels={'app': 'web', 'version': '1.0'},
674
name='web-server'
675
)
676
677
client.start(container)
678
```