docker-pyo3 0.3.1

Python bindings to the docker-api-rs crate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
# docker-pyo3

Python bindings to the Rust `docker_api` crate.

## Installation

```bash
pip install docker_pyo3
```

## Quick Start

```python
from docker_pyo3 import Docker

# Connect to the daemon
docker = Docker()

# Pull an image
docker.images().pull(image='busybox')

# Build an image
docker.images().build(path="path/to/dockerfile", dockerfile='Dockerfile', tag='test-image')

# Create and start a container
container = docker.containers().create(image='busybox', name='my-container')
container.start()

# List running containers
containers = docker.containers().list()

# Stop and remove the container
container.stop()
container.delete()
```

## API Reference

### Docker Client

The main entry point for interacting with the Docker daemon.

#### `Docker(uri=None)`

Create a new Docker client.

**Parameters:**
- `uri` (str, optional): URI to connect to the Docker daemon. Defaults to system default:
  - Unix: `unix:///var/run/docker.sock`
  - Windows: `tcp://localhost:2375`

**Example:**
```python
# Connect to default socket
docker = Docker()

# Connect to custom socket
docker = Docker("unix:///custom/docker.sock")

# Connect to TCP endpoint
docker = Docker("tcp://localhost:2375")
```

#### Methods

##### `version()`
Get Docker version information.

**Returns:** `dict` - Version information including API version, OS, architecture, etc.

```python
version_info = docker.version()
print(version_info)
```

##### `info()`
Get Docker system information.

**Returns:** `dict` - System information including containers count, images count, storage driver, etc.

```python
info = docker.info()
print(f"Total containers: {info['Containers']}")
```

##### `ping()`
Ping the Docker daemon to verify connectivity.

**Returns:** `dict` - Ping response from the daemon

```python
response = docker.ping()
```

##### `data_usage()`
Get data usage information for Docker objects.

**Returns:** `dict` - Data usage statistics for containers, images, volumes, and build cache

```python
usage = docker.data_usage()
print(f"Images size: {usage['Images']}")
```

##### `containers()`
Get the Containers interface for managing containers.

**Returns:** `Containers` - Interface for container operations

```python
containers = docker.containers()
```

##### `images()`
Get the Images interface for managing images.

**Returns:** `Images` - Interface for image operations

```python
images = docker.images()
```

##### `networks()`
Get the Networks interface for managing networks.

**Returns:** `Networks` - Interface for network operations

```python
networks = docker.networks()
```

##### `volumes()`
Get the Volumes interface for managing volumes.

**Returns:** `Volumes` - Interface for volume operations

```python
volumes = docker.volumes()
```

##### `nodes()`
Get the Nodes interface for managing Swarm nodes.

**Returns:** `Nodes` - Interface for node operations (requires Swarm mode)

```python
nodes = docker.nodes()
```

##### `services()`
Get the Services interface for managing Swarm services.

**Returns:** `Services` - Interface for service operations (requires Swarm mode)

```python
services = docker.services()
```

##### `tasks()`
Get the Tasks interface for managing Swarm tasks.

**Returns:** `Tasks` - Interface for task operations (requires Swarm mode)

```python
tasks = docker.tasks()
```

##### `secrets()`
Get the Secrets interface for managing Swarm secrets.

**Returns:** `Secrets` - Interface for secret operations (requires Swarm mode)

```python
secrets = docker.secrets()
```

##### `configs()`
Get the Configs interface for managing Swarm configs.

**Returns:** `Configs` - Interface for config operations (requires Swarm mode)

```python
configs = docker.configs()
```

##### `plugins()`
Get the Plugins interface for managing Docker plugins.

**Returns:** `Plugins` - Interface for plugin operations

```python
plugins = docker.plugins()
```

---

### Containers

Interface for managing Docker containers.

#### `get(id)`
Get a specific container by ID or name.

**Parameters:**
- `id` (str): Container ID or name

**Returns:** `Container` - Container instance

```python
container = docker.containers().get("my-container")
```

#### `list(all=None, since=None, before=None, sized=None)`
List containers.

**Parameters:**
- `all` (bool, optional): Show all containers (default shows only running)
- `since` (str, optional): Show containers created since this container ID
- `before` (str, optional): Show containers created before this container ID
- `sized` (bool, optional): Include size information

**Returns:** `list[dict]` - List of container information dictionaries

```python
# List only running containers
running = docker.containers().list()

# List all containers
all_containers = docker.containers().list(all=True)

# List with size information
containers_with_size = docker.containers().list(all=True, sized=True)
```

#### `prune()`
Remove stopped containers.

**Returns:** `dict` - Prune results including containers deleted and space reclaimed

```python
result = docker.containers().prune()
print(f"Space reclaimed: {result['SpaceReclaimed']}")
```

#### `create(image, **kwargs)`
Create a new container.

**Parameters:**
- `image` (str): Image name to use for the container
- `attach_stderr` (bool, optional): Attach to stderr
- `attach_stdin` (bool, optional): Attach to stdin
- `attach_stdout` (bool, optional): Attach to stdout
- `auto_remove` (bool, optional): Automatically remove the container when it exits
- `capabilities` (list[str], optional): Linux capabilities to add (e.g., `["NET_ADMIN", "SYS_TIME"]`)
- `command` (list[str], optional): Command to run (e.g., `["/bin/sh", "-c", "echo hello"]`)
- `cpu_shares` (int, optional): CPU shares (relative weight)
- `cpus` (float, optional): Number of CPUs
- `devices` (list[dict], optional): Device mappings, each a dict with `PathOnHost`, `PathInContainer`, `CgroupPermissions`
- `entrypoint` (list[str], optional): Entrypoint (e.g., `["/bin/sh"]`)
- `env` (list[str], optional): Environment variables (e.g., `["VAR=value"]`)
- `expose` (list[dict], optional): Port mappings to expose (e.g., `[{"srcport": 8080, "hostport": 8000, "protocol": "tcp"}]`)
- `extra_hosts` (list[str], optional): Extra host-to-IP mappings (e.g., `["hostname:192.168.1.1"]`)
- `labels` (dict, optional): Labels (e.g., `{"app": "myapp", "env": "prod"}`)
- `links` (list[str], optional): Links to other containers
- `log_driver` (str, optional): Logging driver (e.g., "json-file", "syslog")
- `memory` (int, optional): Memory limit in bytes
- `memory_swap` (int, optional): Total memory limit (memory + swap)
- `name` (str, optional): Container name
- `nano_cpus` (int, optional): CPU quota in units of 10^-9 CPUs
- `network_mode` (str, optional): Network mode (e.g., "bridge", "host", "none")
- `privileged` (bool, optional): Give extended privileges
- `publish` (list[dict], optional): Ports to publish (e.g., `[{"port": 8080, "protocol": "tcp"}]`)
- `publish_all_ports` (bool, optional): Publish all exposed ports to random ports
- `restart_policy` (dict, optional): Restart policy with `name` and `maximum_retry_count`
- `security_options` (list[str], optional): Security options (e.g., `["label=user:USER"]`)
- `stop_signal` (str, optional): Signal to stop the container
- `stop_signal_num` (int, optional): Signal number to stop the container
- `stop_timeout` (timedelta, optional): Timeout for stopping the container
- `tty` (bool, optional): Allocate a pseudo-TTY
- `user` (str, optional): Username or UID
- `userns_mode` (str, optional): User namespace mode
- `volumes` (list[str], optional): Volume bindings (e.g., `["/host:/container:rw"]`)
- `volumes_from` (list[str], optional): Mount volumes from other containers
- `working_dir` (str, optional): Working directory inside the container

**Returns:** `Container` - Created container instance

```python
# Simple container
container = docker.containers().create(
    image='busybox',
    name='my-container'
)

# Container with environment variables
container = docker.containers().create(
    image='busybox',
    name='my-app',
    env=["API_KEY=secret", "ENV=production"],
    command=["/bin/sh", "-c", "echo $ENV"]
)

# Container with port mapping and volumes
container = docker.containers().create(
    image='nginx',
    name='web-server',
    expose=[{"srcport": 80, "hostport": 8080, "protocol": "tcp"}],
    volumes=["/data:/usr/share/nginx/html:ro"]
)

# Container with labels and restart policy
container = docker.containers().create(
    image='redis',
    name='cache',
    labels={"app": "cache", "version": "1.0"},
    restart_policy={"name": "on-failure", "maximum_retry_count": 3}
)

# Container with devices
container = docker.containers().create(
    image='ubuntu',
    devices=[
        {"PathOnHost": "/dev/null", "PathInContainer": "/dev/null1", "CgroupPermissions": "rwm"}
    ]
)
```

---

### Container

Represents an individual Docker container.

#### `id()`
Get the container ID.

**Returns:** `str` - Container ID

```python
container_id = container.id()
```

#### `inspect()`
Inspect the container to get detailed information.

**Returns:** `dict` - Detailed container information including config, state, mounts, etc.

```python
info = container.inspect()
print(f"Status: {info['State']['Status']}")
print(f"IP Address: {info['NetworkSettings']['IPAddress']}")
```

#### `logs(stdout=None, stderr=None, timestamps=None, n_lines=None, all=None, since=None)`
Get container logs.

**Parameters:**
- `stdout` (bool, optional): Include stdout
- `stderr` (bool, optional): Include stderr
- `timestamps` (bool, optional): Include timestamps
- `n_lines` (int, optional): Number of lines to return from the end of logs
- `all` (bool, optional): Return all logs
- `since` (datetime, optional): Only return logs since this datetime

**Returns:** `str` - Container logs

```python
# Get all logs
logs = container.logs(stdout=True, stderr=True)

# Get last 100 lines
logs = container.logs(stdout=True, n_lines=100)
```

#### `start()`
Start the container.

**Returns:** `None`

```python
container.start()
```

#### `stop(wait=None)`
Stop the container.

**Parameters:**
- `wait` (timedelta, optional): Time to wait before killing the container

**Returns:** `None`

```python
from datetime import timedelta

# Stop immediately
container.stop()

# Wait 30 seconds before force killing
container.stop(wait=timedelta(seconds=30))
```

#### `restart(wait=None)`
Restart the container.

**Parameters:**
- `wait` (timedelta, optional): Time to wait before killing the container

**Returns:** `None`

```python
container.restart()
```

#### `kill(signal=None)`
Kill the container by sending a signal.

**Parameters:**
- `signal` (str, optional): Signal to send (e.g., "SIGKILL", "SIGTERM")

**Returns:** `None`

```python
# Send SIGTERM
container.kill(signal="SIGTERM")

# Send SIGKILL
container.kill(signal="SIGKILL")
```

#### `pause()`
Pause the container.

**Returns:** `None`

```python
container.pause()
```

#### `unpause()`
Unpause the container.

**Returns:** `None`

```python
container.unpause()
```

#### `rename(name)`
Rename the container.

**Parameters:**
- `name` (str): New name for the container

**Returns:** `None`

```python
container.rename("new-container-name")
```

#### `wait()`
Wait for the container to stop.

**Returns:** `dict` - Wait response including status code

```python
result = container.wait()
print(f"Exit code: {result['StatusCode']}")
```

#### `exec(command, env=None, attach_stdout=None, attach_stderr=None, detach_keys=None, tty=None, privileged=None, user=None, working_dir=None)`
Execute a command in the running container.

**Parameters:**
- `command` (list[str]): Command to execute (e.g., `["/bin/sh", "-c", "ls"]`)
- `env` (list[str], optional): Environment variables (e.g., `["VAR=value"]`)
- `attach_stdout` (bool, optional): Attach to stdout
- `attach_stderr` (bool, optional): Attach to stderr
- `detach_keys` (str, optional): Override key sequence for detaching
- `tty` (bool, optional): Allocate a pseudo-TTY
- `privileged` (bool, optional): Run with extended privileges
- `user` (str, optional): Username or UID
- `working_dir` (str, optional): Working directory for the exec session

**Returns:** `None`

```python
# Execute a simple command
container.exec(command=["/bin/sh", "-c", "ls -la"])

# Execute with environment variables
container.exec(
    command=["printenv"],
    env=["MY_VAR=hello"]
)
```

#### `delete()`
Delete the container.

**Returns:** `None`

```python
container.delete()
```

---

### Images

Interface for managing Docker images.

#### `get(name)`
Get a specific image by name, ID, or tag.

**Parameters:**
- `name` (str): Image name, ID, or tag (e.g., "busybox", "busybox:latest")

**Returns:** `Image` - Image instance

```python
image = docker.images().get("busybox:latest")
```

#### `list(all=None, digests=None, filter=None)`
List images.

**Parameters:**
- `all` (bool, optional): Show all images (default hides intermediate images)
- `digests` (bool, optional): Show digests
- `filter` (dict, optional): Filter images by:
  - `{"type": "dangling"}` - dangling images
  - `{"type": "label", "key": "foo", "value": "bar"}` - by label
  - `{"type": "before", "value": "image:tag"}` - images before specified
  - `{"type": "since", "value": "image:tag"}` - images since specified

**Returns:** `list[dict]` - List of image information dictionaries

```python
# List all images
all_images = docker.images().list(all=True)

# List dangling images
dangling = docker.images().list(filter={"type": "dangling"})

# List images with specific label
labeled = docker.images().list(filter={"type": "label", "key": "app", "value": "web"})
```

#### `prune()`
Remove unused images.

**Returns:** `dict` - Prune results including images deleted and space reclaimed

```python
result = docker.images().prune()
print(f"Space reclaimed: {result['SpaceReclaimed']}")
```

#### `build(path, **kwargs)`
Build an image from a Dockerfile.

**Parameters:**
- `path` (str): Path to build context directory
- `dockerfile` (str, optional): Path to Dockerfile relative to build context
- `tag` (str, optional): Tag for the built image (e.g., "myimage:latest")
- `extra_hosts` (str, optional): Extra hosts to add to /etc/hosts
- `remote` (str, optional): Remote repository URL
- `quiet` (bool, optional): Suppress build output
- `nocahe` (bool, optional): Do not use cache when building
- `pull` (str, optional): Attempt to pull newer version of base image
- `rm` (bool, optional): Remove intermediate containers after build
- `forcerm` (bool, optional): Always remove intermediate containers
- `memory` (int, optional): Memory limit in bytes
- `memswap` (int, optional): Total memory limit (memory + swap)
- `cpu_shares` (int, optional): CPU shares (relative weight)
- `cpu_set_cpus` (str, optional): CPUs to allow execution (e.g., "0-3", "0,1")
- `cpu_period` (int, optional): CPU CFS period in microseconds
- `cpu_quota` (int, optional): CPU CFS quota in microseconds
- `shm_size` (int, optional): Size of /dev/shm in bytes
- `squash` (bool, optional): Squash newly built layers into single layer
- `network_mode` (str, optional): Network mode (e.g., "bridge", "host", "none")
- `platform` (str, optional): Target platform (e.g., "linux/amd64")
- `target` (str, optional): Build stage to target
- `outputs` (str, optional): Output configuration
- `labels` (dict, optional): Labels (e.g., `{"version": "1.0"}`)

**Returns:** `dict` - Build result information

```python
# Simple build
docker.images().build(
    path="/path/to/context",
    dockerfile="Dockerfile",
    tag="myapp:latest"
)

# Build with labels and no cache
docker.images().build(
    path="/path/to/context",
    tag="myapp:v1.0",
    nocahe=True,
    labels={"version": "1.0", "env": "production"}
)

# Build with resource limits
docker.images().build(
    path="/path/to/context",
    tag="myapp:latest",
    memory=1073741824,  # 1GB
    cpu_shares=512
)
```

#### `pull(image=None, src=None, repo=None, tag=None, auth_password=None, auth_token=None)`
Pull an image from a registry.

**Parameters:**
- `image` (str, optional): Image name to pull (e.g., "busybox", "ubuntu:latest")
- `src` (str, optional): Source repository
- `repo` (str, optional): Repository to pull from
- `tag` (str, optional): Tag to pull
- `auth_password` (dict, optional): Password authentication with `username`, `password`, `email`, `server_address`
- `auth_token` (dict, optional): Token authentication with `identity_token`

**Returns:** `dict` - Pull result information

```python
# Pull public image
docker.images().pull(image="busybox:latest")

# Pull with authentication
docker.images().pull(
    image="myregistry.com/myapp:latest",
    auth_password={
        "username": "user",
        "password": "pass",
        "server_address": "myregistry.com"
    }
)

# Pull with token authentication
docker.images().pull(
    image="myregistry.com/myapp:latest",
    auth_token={"identity_token": "my-token"}
)
```

---

### Image

Represents an individual Docker image.

#### `name()`
Get the image name.

**Returns:** `str` - Image name

```python
name = image.name()
```

#### `inspect()`
Inspect the image to get detailed information.

**Returns:** `dict` - Detailed image information including config, layers, etc.

```python
info = image.inspect()
print(f"Size: {info['Size']}")
print(f"Architecture: {info['Architecture']}")
```

#### `delete()`
Delete the image.

**Returns:** `str` - Deletion result information

```python
result = image.delete()
```

#### `history()`
Get the image history.

**Returns:** `str` - Image history information

```python
history = image.history()
```

#### `export(path=None)`
Export the image to a tar file.

**Parameters:**
- `path` (str, optional): Path to save the exported tar file

**Returns:** `str` - Path to the exported file

```python
exported_path = image.export(path="/tmp/myimage.tar")
```

#### `tag(repo=None, tag=None)`
Tag the image with a new name and/or tag.

**Parameters:**
- `repo` (str, optional): Repository name (e.g., "myrepo/myimage")
- `tag` (str, optional): Tag name (e.g., "v1.0", "latest")

**Returns:** `None`

```python
# Tag with new repository
image.tag(repo="myrepo/myimage", tag="latest")

# Tag with version
image.tag(repo="myrepo/myimage", tag="v1.0")
```

#### `push(auth_password=None, auth_token=None, tag=None)`
Push the image to a registry.

**Parameters:**
- `auth_password` (dict, optional): Password authentication with `username`, `password`, `email`, `server_address`
- `auth_token` (dict, optional): Token authentication with `identity_token`
- `tag` (str, optional): Tag to push

**Returns:** `None`

```python
# Push with authentication
image.push(
    auth_password={
        "username": "user",
        "password": "pass",
        "server_address": "myregistry.com"
    },
    tag="latest"
)
```

---

### Networks

Interface for managing Docker networks.

#### `get(id)`
Get a specific network by ID or name.

**Parameters:**
- `id` (str): Network ID or name

**Returns:** `Network` - Network instance

```python
network = docker.networks().get("my-network")
```

#### `list()`
List all networks.

**Returns:** `list[dict]` - List of network information dictionaries

```python
networks = docker.networks().list()
for network in networks:
    print(f"{network['Name']}: {network['Driver']}")
```

#### `prune()`
Remove unused networks.

**Returns:** `dict` - Prune results including networks deleted

```python
result = docker.networks().prune()
```

#### `create(name, **kwargs)`
Create a new network.

**Parameters:**
- `name` (str): Network name
- `check_duplicate` (bool, optional): Check for duplicate networks with the same name
- `driver` (str, optional): Network driver (e.g., "bridge", "overlay")
- `internal` (bool, optional): Restrict external access to the network
- `attachable` (bool, optional): Enable manual container attachment
- `ingress` (bool, optional): Create an ingress network
- `enable_ipv6` (bool, optional): Enable IPv6 networking
- `options` (dict, optional): Driver-specific options
- `labels` (dict, optional): Labels (e.g., `{"env": "prod"}`)

**Returns:** `Network` - Created network instance

```python
# Simple bridge network
network = docker.networks().create(name="my-network")

# Custom network with options
network = docker.networks().create(
    name="app-network",
    driver="bridge",
    labels={"app": "myapp", "env": "production"},
    options={"com.docker.network.bridge.name": "docker1"}
)

# Internal network
network = docker.networks().create(
    name="internal-network",
    driver="bridge",
    internal=True
)
```

---

### Network

Represents an individual Docker network.

#### `id()`
Get the network ID.

**Returns:** `str` - Network ID

```python
network_id = network.id()
```

#### `inspect()`
Inspect the network to get detailed information.

**Returns:** `dict` - Detailed network information including config, containers, etc.

```python
info = network.inspect()
print(f"Subnet: {info['IPAM']['Config'][0]['Subnet']}")
```

#### `delete()`
Delete the network.

**Returns:** `None`

```python
network.delete()
```

#### `connect(container_id, **kwargs)`
Connect a container to this network.

**Parameters:**
- `container_id` (str): Container ID or name to connect
- `aliases` (list[str], optional): Network aliases for the container
- `links` (list[str], optional): Links to other containers
- `network_id` (str, optional): Network ID
- `endpoint_id` (str, optional): Endpoint ID
- `gateway` (str, optional): IPv4 gateway address
- `ipv4` (str, optional): IPv4 address for the container
- `prefix_len` (int, optional): IPv4 prefix length
- `ipv6_gateway` (str, optional): IPv6 gateway address
- `ipv6` (str, optional): IPv6 address for the container
- `ipv6_prefix_len` (int, optional): IPv6 prefix length
- `mac` (str, optional): MAC address
- `driver_opts` (dict, optional): Driver-specific options
- `ipam_config` (dict, optional): IPAM configuration with `ipv4`, `ipv6`, `link_local_ips`

**Returns:** `None`

```python
# Simple connect
network.connect("my-container")

# Connect with custom IP and aliases
network.connect(
    "my-container",
    ipv4="172.20.0.5",
    aliases=["app", "web"]
)

# Connect with IPAM configuration
network.connect(
    "my-container",
    ipam_config={
        "ipv4": "172.20.0.10",
        "ipv6": "2001:db8::10"
    }
)
```

#### `disconnect(container_id, force=None)`
Disconnect a container from this network.

**Parameters:**
- `container_id` (str): Container ID or name to disconnect
- `force` (bool, optional): Force disconnect even if container is running

**Returns:** `None`

```python
# Graceful disconnect
network.disconnect("my-container")

# Force disconnect
network.disconnect("my-container", force=True)
```

---

### Volumes

Interface for managing Docker volumes.

#### `get(name)`
Get a specific volume by name.

**Parameters:**
- `name` (str): Volume name

**Returns:** `Volume` - Volume instance

```python
volume = docker.volumes().get("my-volume")
```

#### `list()`
List all volumes.

**Returns:** `dict` - Volume list information

```python
volumes_info = docker.volumes().list()
for volume in volumes_info['Volumes']:
    print(f"{volume['Name']}: {volume['Driver']}")
```

#### `prune()`
Remove unused volumes.

**Returns:** `dict` - Prune results including volumes deleted and space reclaimed

```python
result = docker.volumes().prune()
print(f"Space reclaimed: {result['SpaceReclaimed']}")
```

#### `create(name=None, driver=None, driver_opts=None, labels=None)`
Create a new volume.

**Parameters:**
- `name` (str, optional): Volume name
- `driver` (str, optional): Volume driver (e.g., "local")
- `driver_opts` (dict, optional): Driver-specific options
- `labels` (dict, optional): Labels (e.g., `{"env": "prod"}`)

**Returns:** `dict` - Created volume information

```python
# Simple volume
volume_info = docker.volumes().create(name="my-volume")

# Volume with labels
volume_info = docker.volumes().create(
    name="app-data",
    labels={"app": "myapp", "env": "production"}
)

# Volume with driver options
volume_info = docker.volumes().create(
    name="tmpfs-volume",
    driver="local",
    driver_opts={"type": "tmpfs", "device": "tmpfs"}
)
```

---

### Volume

Represents an individual Docker volume.

#### `name()`
Get the volume name.

**Returns:** `str` - Volume name

```python
volume_name = volume.name()
```

#### `inspect()`
Inspect the volume to get detailed information.

**Returns:** `dict` - Detailed volume information including driver, mountpoint, etc.

```python
info = volume.inspect()
print(f"Mountpoint: {info['Mountpoint']}")
print(f"Driver: {info['Driver']}")
```

#### `delete()`
Delete the volume.

**Returns:** `None`

```python
volume.delete()
```

---

### Docker Compose

The compose module provides Docker Compose-like functionality for managing multi-container applications.

#### Parsing Compose Files

##### `parse_compose_file(path)`
Parse a Docker Compose file.

**Parameters:**
- `path` (str): Path to the compose file (docker-compose.yml)

**Returns:** `ComposeFile` - Parsed compose file instance

```python
from docker_pyo3.compose import parse_compose_file

compose = parse_compose_file("/path/to/docker-compose.yml")
```

##### `parse_compose_string(content)`
Parse Docker Compose content from a string.

**Parameters:**
- `content` (str): YAML content of the compose file

**Returns:** `ComposeFile` - Parsed compose file instance

```python
from docker_pyo3.compose import parse_compose_string

compose_content = """
version: '3.8'
services:
  web:
    image: nginx
    ports:
      - "8080:80"
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: secret
"""
compose = parse_compose_string(compose_content)
```

#### ComposeFile

Represents a parsed Docker Compose file.

##### `service_names()`
Get list of service names defined in the compose file.

**Returns:** `list[str]` - List of service names

```python
services = compose.service_names()  # ['web', 'db']
```

##### `network_names()`
Get list of network names defined in the compose file.

**Returns:** `list[str]` - List of network names

##### `volume_names()`
Get list of volume names defined in the compose file.

**Returns:** `list[str]` - List of volume names

##### `get_service(name)`
Get configuration for a specific service.

**Parameters:**
- `name` (str): Service name

**Returns:** `dict` or `None` - Service configuration or None if not found

```python
web_config = compose.get_service("web")
print(web_config["image"])  # 'nginx'
```

##### `to_dict()`
Convert the compose file to a dictionary.

**Returns:** `dict` - The full compose configuration

#### ComposeProject

Manages a Docker Compose project (networks, volumes, containers).

##### `ComposeProject(docker, compose_file, project_name)`
Create a new compose project.

**Parameters:**
- `docker` (Docker): Docker client instance
- `compose_file` (ComposeFile): Parsed compose file
- `project_name` (str): Name prefix for all created resources

```python
from docker_pyo3 import Docker
from docker_pyo3.compose import parse_compose_file, ComposeProject

docker = Docker()
compose = parse_compose_file("docker-compose.yml")
project = ComposeProject(docker, compose, "myapp")
```

##### `up(detach=None)`
Bring up the compose project (create networks, volumes, containers).

**Parameters:**
- `detach` (bool, optional): Run containers in background (default: True)

**Returns:** `dict` - Results including created network IDs, volume names, and container IDs

```python
result = project.up()
print(f"Created containers: {result['containers']}")
```

##### `down(remove_volumes=None, remove_networks=None, timeout=None)`
Bring down the compose project.

**Parameters:**
- `remove_volumes` (bool, optional): Also remove named volumes (default: False)
- `remove_networks` (bool, optional): Also remove networks (default: True)
- `timeout` (int, optional): Timeout in seconds for stopping containers (default: 10)

**Returns:** `dict` - Results including removed resources

```python
project.down(remove_volumes=True)
```

##### `ps()`
List container IDs for this project.

**Returns:** `list[str]` - List of container IDs

##### `ps_detailed()`
Get detailed information about project containers.

**Returns:** `list[dict]` - List of container info with id, name, service, state, status, image

```python
containers = project.ps_detailed()
for c in containers:
    print(f"{c['service']}: {c['state']}")
```

##### `start()`
Start all stopped containers in the project.

**Returns:** `list[str]` - List of started container IDs

##### `stop(timeout=None)`
Stop all running containers.

**Parameters:**
- `timeout` (int, optional): Timeout in seconds (default: 10)

**Returns:** `list[str]` - List of stopped container IDs

##### `restart(timeout=None)`
Restart all containers.

**Parameters:**
- `timeout` (int, optional): Timeout in seconds (default: 10)

**Returns:** `list[str]` - List of restarted container IDs

##### `pause()`
Pause all running containers.

**Returns:** `list[str]` - List of paused container IDs

##### `unpause()`
Unpause all paused containers.

**Returns:** `list[str]` - List of unpaused container IDs

##### `pull()`
Pull images for all services.

**Returns:** `list[str]` - List of pulled images

##### `build(no_cache=None, pull=None)`
Build images for services with build configurations.

**Parameters:**
- `no_cache` (bool, optional): Do not use cache (default: False)
- `pull` (bool, optional): Pull newer base images (default: False)

**Returns:** `list[str]` - List of built services

##### `logs(service=None, tail=None, timestamps=None)`
Get logs from containers.

**Parameters:**
- `service` (str, optional): Only get logs from this service
- `tail` (int, optional): Number of lines from end
- `timestamps` (bool, optional): Include timestamps (default: False)

**Returns:** `dict[str, str]` - Mapping of container ID to logs

```python
logs = project.logs(service="web", tail=100)
```

##### `top(ps_args=None)`
Get running processes from containers.

**Parameters:**
- `ps_args` (str, optional): Arguments to pass to ps command

**Returns:** `dict[str, dict]` - Mapping of container ID to process info

##### `config()`
Get the compose configuration as a dictionary.

**Returns:** `dict` - The compose configuration

##### `exec(service, command, user=None, workdir=None, env=None, privileged=None, tty=None)`
Execute a command in a running service container.

**Parameters:**
- `service` (str): Service name
- `command` (list[str]): Command to execute
- `user` (str, optional): User to run as
- `workdir` (str, optional): Working directory
- `env` (list[str], optional): Environment variables (e.g., `["VAR=value"]`)
- `privileged` (bool, optional): Extended privileges (default: False)
- `tty` (bool, optional): Allocate pseudo-TTY (default: False)

**Returns:** `str` - Command output

```python
output = project.exec("web", ["ls", "-la", "/app"])

# With environment variables
output = project.exec(
    "web",
    ["sh", "-c", "echo $MY_VAR"],
    env=["MY_VAR=hello"]
)
```

##### `run(service, command=None, user=None, workdir=None, env=None, rm=None, detach=None)`
Run a one-off command in a new container.

**Parameters:**
- `service` (str): Service name
- `command` (list[str], optional): Command to execute (uses service default if not provided)
- `user` (str, optional): User to run as
- `workdir` (str, optional): Working directory
- `env` (list[str], optional): Additional environment variables
- `rm` (bool, optional): Remove container after exit (default: True)
- `detach` (bool, optional): Run in background (default: False)

**Returns:** `dict` - Result with container_id, output (if not detached), exit_code

```python
# Run a one-off command
result = project.run("web", ["python", "manage.py", "migrate"])
print(result["output"])

# Run detached
result = project.run("worker", ["celery", "worker"], detach=True)
print(f"Container ID: {result['container_id']}")
```

---

### Plugins

Interface for managing Docker plugins.

#### `Plugins.get(name)`
Get a specific plugin by name.

**Parameters:**
- `name` (str): Plugin name (e.g., "vieux/sshfs:latest")

**Returns:** `Plugin` - Plugin instance

```python
plugins = docker.plugins()
plugin = plugins.get("vieux/sshfs:latest")
```

#### `Plugins.list()`
List all installed plugins.

**Returns:** `list[dict]` - List of plugin information

```python
plugins_list = docker.plugins().list()
for p in plugins_list:
    print(f"{p['Name']}: {'enabled' if p['Enabled'] else 'disabled'}")
```

#### `Plugins.list_by_capability(capability)`
List plugins filtered by capability.

**Parameters:**
- `capability` (str): Capability filter (e.g., "volumedriver", "networkdriver")

**Returns:** `list[dict]` - List of matching plugins

```python
volume_plugins = docker.plugins().list_by_capability("volumedriver")
```

#### `Plugin.name()`
Get the plugin name.

**Returns:** `str` - Plugin name

#### `Plugin.inspect()`
Inspect the plugin for detailed information.

**Returns:** `dict` - Plugin details including settings, config, enabled state

```python
info = plugin.inspect()
print(f"Enabled: {info['Enabled']}")
```

#### `Plugin.enable(timeout=None)`
Enable the plugin.

**Parameters:**
- `timeout` (int, optional): Timeout in seconds

**Returns:** `None`

```python
plugin.enable()
```

#### `Plugin.disable()`
Disable the plugin.

**Returns:** `None`

```python
plugin.disable()
```

#### `Plugin.remove()`
Remove the plugin (must be disabled first).

**Returns:** `dict` - Information about removed plugin

```python
plugin.disable()
plugin.remove()
```

#### `Plugin.force_remove()`
Forcefully remove the plugin (even if enabled).

**Returns:** `dict` - Information about removed plugin

#### `Plugin.push()`
Push the plugin to a registry.

**Returns:** `None`

#### `Plugin.create(path)`
Create a plugin from a tar archive.

**Parameters:**
- `path` (str): Path to tar archive with rootfs and config.json

**Returns:** `None`

---

### Swarm Mode Operations

These operations require Docker to be running in Swarm mode.

#### Nodes

Interface for managing Swarm nodes.

##### `Nodes.get(id)`
Get a specific node by ID or name.

**Parameters:**
- `id` (str): Node ID or name

**Returns:** `Node` - Node instance

##### `Nodes.list()`
List all nodes in the swarm.

**Returns:** `list[dict]` - List of node information

```python
nodes = docker.nodes().list()
for node in nodes:
    print(f"{node['ID']}: {node['Status']['State']}")
```

##### `Node.id()`
Get the node ID.

**Returns:** `str` - Node ID

##### `Node.inspect()`
Inspect the node for detailed information.

**Returns:** `dict` - Node details including status, spec, description

```python
info = node.inspect()
print(f"Role: {info['Spec']['Role']}")
print(f"Availability: {info['Spec']['Availability']}")
```

##### `Node.delete()`
Delete the node from the swarm.

**Returns:** `None`

##### `Node.force_delete()`
Force delete the node from the swarm.

**Returns:** `None`

##### `Node.update(version, name=None, role=None, availability=None, labels=None)`
Update node configuration.

**Parameters:**
- `version` (str): Node version (from inspect)
- `name` (str, optional): Node name
- `role` (str, optional): Role ("worker" or "manager")
- `availability` (str, optional): Availability ("active", "pause", or "drain")
- `labels` (dict, optional): Node labels

```python
info = node.inspect()
version = str(info['Version']['Index'])
node.update(version, availability="drain", labels={"env": "production"})
```

#### Services

Interface for managing Swarm services.

##### `Services.get(id)`
Get a specific service by ID or name.

**Parameters:**
- `id` (str): Service ID or name

**Returns:** `Service` - Service instance

##### `Services.list()`
List all services in the swarm.

**Returns:** `list[dict]` - List of service information

```python
services = docker.services().list()
for svc in services:
    print(f"{svc['Spec']['Name']}: {svc['Spec']['Mode']}")
```

##### `Service.id()`
Get the service ID.

**Returns:** `str` - Service ID

##### `Service.inspect()`
Inspect the service for detailed information.

**Returns:** `dict` - Service details including spec, endpoint, update status

##### `Service.delete()`
Delete the service from the swarm.

**Returns:** `None`

##### `Service.logs(stdout=None, stderr=None, timestamps=None, n_lines=None, all=None, since=None)`
Get service logs.

**Parameters:**
- `stdout` (bool, optional): Include stdout
- `stderr` (bool, optional): Include stderr
- `timestamps` (bool, optional): Include timestamps
- `n_lines` (int, optional): Number of lines from end
- `all` (bool, optional): Return all logs
- `since` (datetime, optional): Only logs since this time

**Returns:** `str` - Service logs

#### Secrets

Interface for managing Swarm secrets.

##### `Secrets.get(id)`
Get a specific secret by ID or name.

**Parameters:**
- `id` (str): Secret ID or name

**Returns:** `Secret` - Secret instance

##### `Secrets.list()`
List all secrets in the swarm.

**Returns:** `list[dict]` - List of secret information

##### `Secrets.create(name, data, labels=None)`
Create a new secret.

**Parameters:**
- `name` (str): Secret name
- `data` (str): Secret data (base64 encoded automatically)
- `labels` (dict, optional): Labels

**Returns:** `Secret` - Created secret instance

```python
secret = docker.secrets().create(
    name="db_password",
    data="super_secret_123",
    labels={"app": "myapp"}
)
```

##### `Secret.id()`
Get the secret ID.

**Returns:** `str` - Secret ID

##### `Secret.inspect()`
Inspect the secret (data not returned for security).

**Returns:** `dict` - Secret metadata

##### `Secret.delete()`
Delete the secret.

**Returns:** `None`

#### Configs

Interface for managing Swarm configs (non-sensitive configuration data).

##### `Configs.get(id)`
Get a specific config by ID or name.

**Parameters:**
- `id` (str): Config ID or name

**Returns:** `Config` - Config instance

##### `Configs.list()`
List all configs in the swarm.

**Returns:** `list[dict]` - List of config information

##### `Configs.create(name, data, labels=None)`
Create a new config.

**Parameters:**
- `name` (str): Config name
- `data` (str): Config data (base64 encoded automatically)
- `labels` (dict, optional): Labels

**Returns:** `Config` - Created config instance

```python
config = docker.configs().create(
    name="nginx_config",
    data="server { listen 80; }",
    labels={"app": "web"}
)
```

##### `Config.id()`
Get the config ID.

**Returns:** `str` - Config ID

##### `Config.inspect()`
Inspect the config.

**Returns:** `dict` - Config details

##### `Config.delete()`
Delete the config.

**Returns:** `None`

#### Tasks

Interface for managing Swarm tasks (container instances of services).

##### `Tasks.get(id)`
Get a specific task by ID.

**Parameters:**
- `id` (str): Task ID

**Returns:** `Task` - Task instance

##### `Tasks.list()`
List all tasks in the swarm.

**Returns:** `list[dict]` - List of task information

```python
tasks = docker.tasks().list()
for task in tasks:
    print(f"{task['ID']}: {task['Status']['State']}")
```

##### `Task.id()`
Get the task ID.

**Returns:** `str` - Task ID

##### `Task.inspect()`
Inspect the task for detailed information.

**Returns:** `dict` - Task details including status, spec, assigned node

##### `Task.logs(stdout=None, stderr=None, timestamps=None, n_lines=None, all=None, since=None)`
Get task logs.

**Parameters:**
- Same as Service.logs()

**Returns:** `str` - Task logs

---

## Complete Examples

### Building and Running a Web Application

```python
from docker_pyo3 import Docker

docker = Docker()

# Build the application image
docker.images().build(
    path="/path/to/app",
    dockerfile="Dockerfile",
    tag="myapp:latest",
    labels={"version": "1.0", "env": "production"}
)

# Create a custom network
network = docker.networks().create(
    name="app-network",
    driver="bridge"
)

# Create a volume for data persistence
docker.volumes().create(
    name="app-data",
    labels={"app": "myapp"}
)

# Create and start the application container
app_container = docker.containers().create(
    image="myapp:latest",
    name="myapp-instance",
    env=["ENV=production", "PORT=8080"],
    expose=[{"srcport": 8080, "hostport": 8080, "protocol": "tcp"}],
    volumes=["app-data:/data:rw"],
    labels={"app": "myapp", "tier": "web"},
    restart_policy={"name": "on-failure", "maximum_retry_count": 3}
)

# Connect to the custom network
network.connect("myapp-instance")

# Start the container
app_container.start()

# Check logs
logs = app_container.logs(stdout=True, stderr=True, n_lines=50)
print(logs)

# Inspect running container
info = app_container.inspect()
print(f"Container IP: {info['NetworkSettings']['Networks']['app-network']['IPAddress']}")

# Stop and cleanup
app_container.stop()
app_container.delete()
network.disconnect("myapp-instance")
network.delete()
```

### Managing Multiple Containers

```python
from docker_pyo3 import Docker

docker = Docker()

# Pull required images
docker.images().pull(image="nginx:latest")
docker.images().pull(image="redis:latest")

# Create a custom network for the application
network = docker.networks().create(name="app-tier")

# Create Redis container
redis = docker.containers().create(
    image="redis:latest",
    name="redis",
    labels={"tier": "cache"}
)
redis.start()
network.connect("redis", aliases=["cache"])

# Create Nginx container linked to Redis
nginx = docker.containers().create(
    image="nginx:latest",
    name="web",
    expose=[{"srcport": 80, "hostport": 8080, "protocol": "tcp"}],
    labels={"tier": "web"},
    links=["redis:cache"]
)
nginx.start()
network.connect("web")

# List all running containers
containers = docker.containers().list()
for container in containers:
    print(f"{container['Names'][0]}: {container['Status']}")

# Cleanup
for container_name in ["web", "redis"]:
    c = docker.containers().get(container_name)
    c.stop()
    c.delete()

network.delete()
```

---

## Why does this exist?

Python already has the `docker` package, so why create another one?

This library is designed specifically for **Rust projects that expose Python as a plugin interface**. If you:
- Just need Docker in Python → Use `pip install docker`
- Just need Docker in Rust → Use the `docker_api` crate
- Need to add a Python interface to containers in a Rust library/binary via `pyo3` → This library provides ready-to-use bindings

## Embedding in Rust Projects

You can embed `docker-pyo3` in your Rust application using PyO3. Here's an example:

```rust
use pyo3::prelude::*;
use pyo3::wrap_pymodule;

#[pymodule]
fn root_module(_py: Python, m: &PyModule) -> PyResult<()> {
    // Register your custom functionality
    m.add_function(wrap_pyfunction!(main, m)?)?;

    // Add docker-pyo3 as a submodule
    m.add_wrapped(wrap_pymodule!(_integrations))?;

    // Register submodules in sys.modules for proper imports
    let sys = PyModule::import(_py, "sys")?;
    let sys_modules: &PyDict = sys.getattr("modules")?.downcast()?;
    sys_modules.set_item("root_module._integrations", m.getattr("_integrations")?)?;
    sys_modules.set_item("root_module._integrations.docker", m.getattr("_integrations")?.getattr("docker")?)?;

    Ok(())
}

#[pymodule]
fn _integrations(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_wrapped(wrap_pymodule!(docker))?;
    Ok(())
}

#[pymodule]
fn docker(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<docker_pyo3::Pyo3Docker>()?;
    m.add_wrapped(wrap_pymodule!(docker_pyo3::image::image))?;
    m.add_wrapped(wrap_pymodule!(docker_pyo3::container::container))?;
    m.add_wrapped(wrap_pymodule!(docker_pyo3::network::network))?;
    m.add_wrapped(wrap_pymodule!(docker_pyo3::volume::volume))?;
    Ok(())
}
```

This creates the following Python namespace structure:
- `root_module._integrations.docker.Docker`
- `root_module._integrations.docker.image.Images`, `Image`
- `root_module._integrations.docker.container.Containers`, `Container`
- `root_module._integrations.docker.network.Networks`, `Network`
- `root_module._integrations.docker.volume.Volumes`, `Volume`

## License

GPL-3.0-only

## Contributing

Contributions are welcome! Please see the test suite in `py_test/` for examples of the full API in action.