0
# System Operations
1
2
System-level Docker operations including information retrieval, cleanup, and monitoring. These operations provide insights into Docker daemon status, resource usage, and system-wide management.
3
4
## Capabilities
5
6
### System Information
7
8
Retrieve comprehensive information about the Docker system and daemon.
9
10
```python { .api }
11
def info() -> SystemInfo:
12
"""
13
Get system-wide information about Docker.
14
15
Returns:
16
- SystemInfo object with detailed system information
17
"""
18
```
19
20
### Resource Usage Analysis
21
22
Analyze disk usage and resource consumption across Docker objects.
23
24
```python { .api }
25
def df() -> DiskFreeResult:
26
"""
27
Show docker filesystem usage.
28
29
Returns:
30
- DiskFreeResult with breakdown of space usage by type
31
"""
32
```
33
34
### System Cleanup
35
36
Perform system-wide cleanup operations to reclaim disk space.
37
38
```python { .api }
39
def prune(
40
*,
41
all: bool = False,
42
volumes: bool = False,
43
filters: Optional[Dict[str, str]] = None,
44
force: bool = False
45
) -> Dict[str, Any]:
46
"""
47
Remove unused Docker objects system-wide.
48
49
Parameters:
50
- all: Remove all unused objects, not just dangling ones
51
- volumes: Also remove unused volumes
52
- filters: Filters to apply to cleanup
53
- force: Don't prompt for confirmation
54
55
Returns:
56
- Information about removed objects and space reclaimed
57
"""
58
```
59
60
### Event Monitoring
61
62
Monitor Docker daemon events in real-time.
63
64
```python { .api }
65
def events(
66
*,
67
since: Optional[str] = None,
68
until: Optional[str] = None,
69
filters: Optional[Dict[str, str]] = None,
70
format: Optional[str] = None
71
) -> Iterator[Dict[str, Any]]:
72
"""
73
Get real-time events from Docker daemon.
74
75
Parameters:
76
- since: Show events since timestamp
77
- until: Show events until timestamp
78
- filters: Filter events (container, image, volume, network, daemon, etc.)
79
- format: Output format template
80
81
Returns:
82
- Iterator of event dictionaries
83
"""
84
```
85
86
## Usage Examples
87
88
### System Monitoring
89
90
```python
91
from python_on_whales import docker
92
93
# Get comprehensive system information
94
info = docker.system.info()
95
print(f"Docker Version: {info.server_version}")
96
print(f"Architecture: {info.architecture}")
97
print(f"Operating System: {info.operating_system}")
98
print(f"Total Memory: {info.mem_total}")
99
print(f"Containers: {info.containers} (Running: {info.containers_running})")
100
print(f"Images: {info.images}")
101
102
# Check disk usage
103
usage = docker.system.df()
104
print(f"Images: {len(usage.images)} using {usage.images_size}")
105
print(f"Containers: {len(usage.containers)} using {usage.containers_size}")
106
print(f"Volumes: {len(usage.volumes)} using {usage.volumes_size}")
107
print(f"Build Cache: {usage.build_cache_size}")
108
```
109
110
### Resource Cleanup
111
112
```python
113
# Perform comprehensive cleanup
114
cleanup_result = docker.system.prune(
115
all=True,
116
volumes=True,
117
force=True
118
)
119
120
print(f"Containers removed: {cleanup_result.get('ContainersDeleted', 0)}")
121
print(f"Networks removed: {cleanup_result.get('NetworksDeleted', 0)}")
122
print(f"Images removed: {cleanup_result.get('ImagesDeleted', 0)}")
123
print(f"Volumes removed: {cleanup_result.get('VolumesDeleted', 0)}")
124
print(f"Space reclaimed: {cleanup_result.get('SpaceReclaimed', 0)}")
125
126
# Targeted cleanup with filters
127
filtered_cleanup = docker.system.prune(
128
filters={"until": "24h"},
129
force=True
130
)
131
```
132
133
### Event Monitoring
134
135
```python
136
import json
137
from datetime import datetime
138
139
# Monitor all events
140
print("Monitoring Docker events (Ctrl+C to stop)...")
141
try:
142
for event in docker.system.events():
143
timestamp = datetime.fromtimestamp(event['time'])
144
print(f"[{timestamp}] {event['Type']}: {event['Action']} - {event.get('Actor', {}).get('Attributes', {}).get('name', 'N/A')}")
145
except KeyboardInterrupt:
146
print("Stopped monitoring events")
147
148
# Monitor specific event types
149
container_events = docker.system.events(
150
filters={"type": "container", "event": ["start", "stop", "die"]}
151
)
152
153
for event in container_events:
154
container_name = event.get('Actor', {}).get('Attributes', {}).get('name', 'unknown')
155
print(f"Container {container_name}: {event['Action']}")
156
157
# Break after 10 events for demo
158
if event['time'] > (datetime.now().timestamp() + 60):
159
break
160
```
161
162
### System Health Checks
163
164
```python
165
def check_docker_health():
166
"""Comprehensive Docker system health check."""
167
try:
168
info = docker.system.info()
169
170
# Check if daemon is responsive
171
print("✓ Docker daemon is responsive")
172
173
# Check system resources
174
if info.mem_total < 2 * 1024 * 1024 * 1024: # Less than 2GB
175
print("⚠ Warning: Low system memory")
176
else:
177
print("✓ System memory looks good")
178
179
# Check storage driver
180
print(f"✓ Storage driver: {info.storage_driver}")
181
182
# Check for warnings
183
if hasattr(info, 'warnings') and info.warnings:
184
print("⚠ System warnings:")
185
for warning in info.warnings:
186
print(f" - {warning}")
187
else:
188
print("✓ No system warnings")
189
190
# Check disk usage
191
usage = docker.system.df()
192
total_size = sum([
193
usage.images_size or 0,
194
usage.containers_size or 0,
195
usage.volumes_size or 0,
196
usage.build_cache_size or 0
197
])
198
199
print(f"✓ Total Docker disk usage: {total_size / (1024**3):.2f} GB")
200
201
return True
202
203
except Exception as e:
204
print(f"✗ Docker health check failed: {e}")
205
return False
206
207
# Run health check
208
if check_docker_health():
209
print("Docker system is healthy!")
210
else:
211
print("Docker system has issues that need attention.")
212
```
213
214
## Types
215
216
```python { .api }
217
class SystemInfo:
218
id: str
219
containers: int
220
containers_running: int
221
containers_paused: int
222
containers_stopped: int
223
images: int
224
storage_driver: str
225
logging_driver: str
226
cgroup_driver: str
227
cgroup_version: str
228
plugins: Dict[str, List[str]]
229
memory_limit: bool
230
swap_limit: bool
231
kernel_memory: bool
232
oom_kill_disable: bool
233
cpu_cfs_period: bool
234
cpu_cfs_quota: bool
235
cpu_shares: bool
236
cpuset: bool
237
pids_limit: bool
238
ipv4_forwarding: bool
239
bridge_nf_iptables: bool
240
bridge_nf_ip6tables: bool
241
debug: bool
242
n_fd: int
243
oom_score_adj: int
244
n_goroutines: int
245
system_time: str
246
logging_driver: str
247
cgroup_driver: str
248
n_events_listener: int
249
kernel_version: str
250
operating_system: str
251
os_type: str
252
architecture: str
253
index_server_address: str
254
registry_config: Dict[str, Any]
255
ncpu: int
256
mem_total: int
257
generic_resources: List[Dict[str, Any]]
258
docker_root_dir: str
259
http_proxy: str
260
https_proxy: str
261
no_proxy: str
262
name: str
263
labels: List[str]
264
experimental_build: bool
265
server_version: str
266
cluster_store: str
267
cluster_advertise: str
268
runtimes: Dict[str, Dict[str, Any]]
269
default_runtime: str
270
swarm: Dict[str, Any]
271
live_restore_enabled: bool
272
isolation: str
273
init_binary: str
274
containerd_commit: Dict[str, str]
275
runc_commit: Dict[str, str]
276
init_commit: Dict[str, str]
277
security_options: List[str]
278
product_license: str
279
warnings: Optional[List[str]]
280
281
class DiskFreeResult:
282
layers_size: Optional[int]
283
images: List[Dict[str, Any]]
284
images_size: Optional[int]
285
containers: List[Dict[str, Any]]
286
containers_size: Optional[int]
287
volumes: List[Dict[str, Any]]
288
volumes_size: Optional[int]
289
build_cache: List[Dict[str, Any]]
290
build_cache_size: Optional[int]
291
292
class DockerEvent:
293
type: str
294
action: str
295
time: int
296
time_nano: int
297
actor: Dict[str, Any]
298
scope: Optional[str]
299
```