0
# Image Management
1
2
Docker image operations including building, pulling, pushing, tagging, and registry interactions with support for multi-platform builds and custom build contexts.
3
4
## Capabilities
5
6
### ImageCollection
7
8
High-level image management operations accessible via `client.images`.
9
10
```python { .api }
11
class ImageCollection:
12
def build(self, **kwargs):
13
"""
14
Build an image from a Dockerfile.
15
16
Args:
17
**kwargs: Build configuration options
18
19
Returns:
20
tuple: (Image, build_logs_generator)
21
22
Common kwargs:
23
path (str): Path to build context directory
24
fileobj (file-like): File-like object containing build context tar
25
dockerfile (str): Path to Dockerfile relative to build context
26
tag (str): Tag for the built image
27
quiet (bool): Suppress build output
28
nocache (bool): Do not use cache when building
29
rm (bool): Remove intermediate containers (default: True)
30
timeout (int): Build timeout in seconds
31
custom_context (bool): Use custom build context
32
encoding (str): Encoding for build context
33
pull (bool): Always pull newer version of base image
34
forcerm (bool): Always remove intermediate containers
35
buildargs (dict): Build-time variables
36
container_limits (dict): Resource limits during build
37
shmsize (int): Shared memory size for build containers
38
labels (dict): Labels to apply to built image
39
cache_from (list): Images to use for build cache
40
target (str): Build target stage in multi-stage Dockerfile
41
network_mode (str): Network mode for build
42
squash (bool): Squash layers into single layer
43
extra_hosts (dict): Extra hosts for build
44
platform (str): Target platform for build
45
isolation (str): Container isolation technology
46
"""
47
48
def get(self, name):
49
"""
50
Get an image by name or ID.
51
52
Args:
53
name (str): Image name, ID, or tag
54
55
Returns:
56
Image: Image instance
57
58
Raises:
59
ImageNotFound: If image doesn't exist
60
"""
61
62
def get_registry_data(self, name, auth_config=None):
63
"""
64
Get image metadata from registry without pulling.
65
66
Args:
67
name (str): Image name with optional tag
68
auth_config (dict): Registry authentication config
69
70
Returns:
71
RegistryData: Registry metadata including digest, platform info
72
"""
73
74
def list(self, name=None, all=False, filters=None):
75
"""
76
List images.
77
78
Args:
79
name (str): Filter by image name
80
all (bool): Include intermediate images
81
filters (dict): Filter results by dangling, label, etc.
82
83
Returns:
84
list[Image]: List of image instances
85
"""
86
87
def load(self, data):
88
"""
89
Load image from tar archive.
90
91
Args:
92
data (bytes or file-like): Tar archive containing image
93
94
Returns:
95
list[Image]: Loaded images
96
"""
97
98
def pull(self, repository, tag=None, all_tags=False, **kwargs):
99
"""
100
Pull an image from registry.
101
102
Args:
103
repository (str): Repository name
104
tag (str): Specific tag to pull (default: latest)
105
all_tags (bool): Pull all tags of repository
106
**kwargs: Additional pull options
107
108
Returns:
109
Image or list[Image]: Pulled image(s)
110
111
Common kwargs:
112
auth_config (dict): Registry authentication
113
platform (str): Target platform
114
stream (bool): Stream pull progress
115
"""
116
117
def push(self, repository, tag=None, **kwargs):
118
"""
119
Push an image to registry.
120
121
Args:
122
repository (str): Repository name to push to
123
tag (str): Tag to push (default: latest)
124
**kwargs: Push options
125
126
Returns:
127
str: Push progress information
128
129
Common kwargs:
130
auth_config (dict): Registry authentication
131
stream (bool): Stream push progress
132
"""
133
134
def search(self, term, limit=25):
135
"""
136
Search Docker Hub for images.
137
138
Args:
139
term (str): Search term
140
limit (int): Maximum results to return
141
142
Returns:
143
list[dict]: Search results with name, description, stars, official status
144
"""
145
146
def prune(self, filters=None):
147
"""
148
Remove unused images.
149
150
Args:
151
filters (dict): Filters for pruning (dangling, until, label)
152
153
Returns:
154
dict: Pruning results with space reclaimed
155
"""
156
157
def prune_builds(self, **kwargs):
158
"""
159
Remove build cache.
160
161
Args:
162
**kwargs: Pruning options
163
164
Returns:
165
dict: Pruning results
166
167
Common kwargs:
168
filters (dict): Build cache filters
169
keep_storage (int): Keep specified amount of storage
170
all (bool): Remove all cache, not just dangling
171
"""
172
```
173
174
### Image Model
175
176
Individual image instance with metadata and operations.
177
178
```python { .api }
179
class Image:
180
"""
181
A Docker image instance.
182
183
Properties:
184
id (str): Full image ID
185
short_id (str): Short image ID (12 characters)
186
tags (list): List of image tags
187
labels (dict): Image labels
188
attrs (dict): Raw image attributes from Docker API
189
"""
190
191
def history(self):
192
"""
193
Get image layer history.
194
195
Returns:
196
list[dict]: Layer history with creation info, size, created by command
197
"""
198
199
def reload(self):
200
"""Refresh image data from Docker daemon."""
201
202
def remove(self, force=False, noprune=False):
203
"""
204
Remove the image.
205
206
Args:
207
force (bool): Force removal even if containers use image
208
noprune (bool): Do not delete untagged parent images
209
210
Returns:
211
list[dict]: Removal results
212
"""
213
214
def save(self, chunk_size=2097152):
215
"""
216
Save image as tar archive.
217
218
Args:
219
chunk_size (int): Chunk size for streaming
220
221
Yields:
222
bytes: Tar archive data chunks
223
"""
224
225
def tag(self, repository, tag=None, **kwargs):
226
"""
227
Tag the image.
228
229
Args:
230
repository (str): Repository name
231
tag (str): Tag name (default: latest)
232
**kwargs: Additional tagging options
233
234
Returns:
235
bool: True if successful
236
"""
237
```
238
239
## Usage Examples
240
241
### Image Building
242
243
```python
244
import docker
245
import io
246
247
client = docker.from_env()
248
249
# Build from Dockerfile in directory
250
image, build_logs = client.images.build(
251
path='/path/to/build/context',
252
tag='my-app:latest',
253
dockerfile='Dockerfile'
254
)
255
256
# Print build logs
257
for log in build_logs:
258
if 'stream' in log:
259
print(log['stream'].strip())
260
261
# Build with custom context
262
dockerfile_content = '''
263
FROM python:3.9-slim
264
COPY . /app
265
WORKDIR /app
266
RUN pip install -r requirements.txt
267
CMD ["python", "app.py"]
268
'''
269
270
# Create build context in memory
271
import tarfile
272
context = io.BytesIO()
273
with tarfile.open(fileobj=context, mode='w') as tar:
274
# Add Dockerfile
275
dockerfile_info = tarfile.TarInfo('Dockerfile')
276
dockerfile_info.size = len(dockerfile_content)
277
tar.addfile(dockerfile_info, io.BytesIO(dockerfile_content.encode()))
278
279
# Add application files
280
tar.add('/local/app.py', arcname='app.py')
281
tar.add('/local/requirements.txt', arcname='requirements.txt')
282
283
context.seek(0)
284
image, logs = client.images.build(
285
fileobj=context,
286
custom_context=True,
287
tag='python-app:latest',
288
buildargs={'VERSION': '1.0'}
289
)
290
```
291
292
### Advanced Build Configuration
293
294
```python
295
# Multi-stage build with target
296
image, logs = client.images.build(
297
path='/app/source',
298
tag='my-app:production',
299
target='production',
300
buildargs={
301
'BUILD_ENV': 'production',
302
'VERSION': '2.1.0'
303
},
304
labels={
305
'version': '2.1.0',
306
'maintainer': 'devops@company.com'
307
},
308
cache_from=['my-app:base', 'my-app:builder'],
309
network_mode='host',
310
platform='linux/amd64',
311
extra_hosts={'api.internal': '192.168.1.100'}
312
)
313
314
# Build with resource limits
315
image, logs = client.images.build(
316
path='/app/source',
317
tag='memory-intensive:latest',
318
container_limits={
319
'memory': 1073741824, # 1GB
320
'memswap': -1,
321
'cpushares': 512
322
},
323
shmsize=268435456 # 256MB
324
)
325
```
326
327
### Image Registry Operations
328
329
```python
330
# Pull specific image
331
image = client.images.pull('nginx:1.21-alpine')
332
print(f"Pulled image: {image.tags}")
333
334
# Pull with authentication
335
auth_config = {
336
'username': 'myuser',
337
'password': 'mypass',
338
'registry': 'private-registry.com'
339
}
340
341
image = client.images.pull(
342
'private-registry.com/my-app:latest',
343
auth_config=auth_config
344
)
345
346
# Pull all tags of repository
347
images = client.images.pull('alpine', all_tags=True)
348
for img in images:
349
print(f"Tags: {img.tags}")
350
351
# Get registry data without pulling
352
registry_data = client.images.get_registry_data(
353
'ubuntu:20.04',
354
auth_config=auth_config
355
)
356
print(f"Digest: {registry_data.id}")
357
print(f"Platform: {registry_data.attrs['platform']}")
358
```
359
360
### Image Management Operations
361
362
```python
363
# List and filter images
364
all_images = client.images.list()
365
for image in all_images:
366
print(f"ID: {image.short_id}, Tags: {image.tags}")
367
368
# Filter images
369
python_images = client.images.list(filters={'reference': 'python:*'})
370
dangling_images = client.images.list(filters={'dangling': True})
371
372
# Get specific image
373
image = client.images.get('nginx:latest')
374
print(f"Image ID: {image.id}")
375
print(f"Labels: {image.labels}")
376
377
# Image operations
378
image.tag('my-nginx:backup')
379
image.tag('registry.example.com/nginx:latest')
380
381
# Get image history
382
history = image.history()
383
for layer in history:
384
print(f"Layer: {layer['Id'][:12]}, Size: {layer['Size']}, Created: {layer['Created']}")
385
386
# Save image to file
387
with open('/tmp/nginx_backup.tar', 'wb') as f:
388
for chunk in image.save():
389
f.write(chunk)
390
```
391
392
### Image Cleanup and Maintenance
393
394
```python
395
# Remove specific image
396
try:
397
client.images.get('old-image:latest').remove(force=True)
398
print("Image removed successfully")
399
except docker.errors.ImageNotFound:
400
print("Image not found")
401
402
# Prune unused images
403
pruned = client.images.prune()
404
print(f"Removed {len(pruned['ImagesDeleted'])} images")
405
print(f"Space reclaimed: {pruned['SpaceReclaimed']} bytes")
406
407
# Prune with filters
408
pruned = client.images.prune(filters={
409
'until': '72h', # Remove images older than 72 hours
410
'label': 'temporary=true'
411
})
412
413
# Clean build cache
414
cache_pruned = client.images.prune_builds()
415
print(f"Build cache reclaimed: {cache_pruned['SpaceReclaimed']} bytes")
416
417
# Remove all build cache
418
cache_pruned = client.images.prune_builds(all=True)
419
```
420
421
### Image Import/Export
422
423
```python
424
# Load images from tar file
425
with open('/tmp/images_backup.tar', 'rb') as f:
426
loaded_images = client.images.load(f.read())
427
428
for image in loaded_images:
429
print(f"Loaded: {image.tags}")
430
431
# Search Docker Hub
432
search_results = client.images.search('python', limit=10)
433
for result in search_results:
434
print(f"Name: {result['name']}")
435
print(f"Description: {result['description']}")
436
print(f"Stars: {result['star_count']}")
437
print(f"Official: {result['is_official']}")
438
print("---")
439
440
# Push to registry
441
auth_config = {
442
'username': 'myuser',
443
'password': 'mytoken',
444
'registry': 'docker.io'
445
}
446
447
# Tag for registry
448
image = client.images.get('my-app:latest')
449
image.tag('myuser/my-app:v1.0')
450
451
# Push with progress
452
push_logs = client.images.push(
453
'myuser/my-app:v1.0',
454
auth_config=auth_config,
455
stream=True
456
)
457
458
for log in push_logs:
459
if 'status' in log:
460
print(f"{log['status']}: {log.get('progress', '')}")
461
```