0
# Image Management
1
2
Comprehensive Docker image operations including pulling from registries, building from Dockerfiles, tagging, pushing, and local management. Supports both public and private registries with authentication and provides complete image lifecycle management capabilities.
3
4
## Capabilities
5
6
### Image Listing and Inspection
7
8
Functions for discovering and examining Docker images in the local system.
9
10
```python { .api }
11
def images(name=None, quiet=False, all=False, viz=False, filters=None):
12
"""
13
List Docker images.
14
15
Parameters:
16
- name (str): Image name to filter by
17
- quiet (bool): Only return image IDs
18
- all (bool): Show all images (including intermediate layers)
19
- viz (bool): Return image tree visualization (deprecated)
20
- filters (dict): Filters to process on image list
21
22
Returns:
23
list: List of image dictionaries with metadata
24
"""
25
26
def inspect_image(image):
27
"""
28
Get detailed information about an image.
29
30
Parameters:
31
- image (str): Image name, ID, or tag
32
33
Returns:
34
dict: Detailed image information including config, layers, and metadata
35
"""
36
37
def history(image):
38
"""
39
Get the history of an image showing layer information.
40
41
Parameters:
42
- image (str): Image name, ID, or tag
43
44
Returns:
45
list: List of layer history entries
46
"""
47
48
def search(term):
49
"""
50
Search Docker Hub for images.
51
52
Parameters:
53
- term (str): Search term
54
55
Returns:
56
list: List of search results from Docker Hub
57
"""
58
```
59
60
### Image Transfer Operations
61
62
Functions for pulling images from registries and pushing local images to remote repositories.
63
64
```python { .api }
65
def pull(repository, tag=None, stream=False, insecure_registry=False,
66
auth_config=None, decode=False):
67
"""
68
Pull an image from a registry.
69
70
Parameters:
71
- repository (str): Repository name (e.g., 'ubuntu', 'library/ubuntu')
72
- tag (str): Image tag (default: 'latest')
73
- stream (bool): Stream pull output as generator
74
- insecure_registry (bool): Allow insecure registry connections
75
- auth_config (dict): Authentication configuration
76
- decode (bool): Decode JSON stream output
77
78
Returns:
79
generator|bytes: Pull output stream or raw data
80
"""
81
82
def push(repository, tag=None, stream=False, insecure_registry=False,
83
auth_config=None, decode=False):
84
"""
85
Push an image to a registry.
86
87
Parameters:
88
- repository (str): Repository name
89
- tag (str): Image tag (default: 'latest')
90
- stream (bool): Stream push output as generator
91
- insecure_registry (bool): Allow insecure registry connections
92
- auth_config (dict): Authentication configuration
93
- decode (bool): Decode JSON stream output
94
95
Returns:
96
generator|bytes: Push output stream or raw data
97
"""
98
```
99
100
### Image Building
101
102
Build Docker images from Dockerfiles or build contexts with comprehensive configuration options.
103
104
```python { .api }
105
def build(path=None, tag=None, quiet=False, fileobj=None, nocache=False,
106
rm=False, stream=False, timeout=None, custom_context=False,
107
encoding=None, pull=False, forcerm=False, dockerfile=None,
108
container_limits=None, decode=False, buildargs=None, gzip=False):
109
"""
110
Build a Docker image from a Dockerfile or build context.
111
112
Parameters:
113
- path (str): Path to build context directory
114
- tag (str): Tag for the built image
115
- quiet (bool): Suppress build output
116
- fileobj (file): File-like object containing Dockerfile or build context
117
- nocache (bool): Do not use cache when building
118
- rm (bool): Remove intermediate containers after build
119
- stream (bool): Stream build output as generator
120
- timeout (int): Timeout for build process
121
- custom_context (bool): Use custom build context
122
- encoding (str): Encoding for build context
123
- pull (bool): Always pull base images
124
- forcerm (bool): Always remove intermediate containers
125
- dockerfile (str): Path to Dockerfile within build context
126
- container_limits (dict): Container resource limits during build
127
- decode (bool): Decode JSON build output
128
- buildargs (dict): Build-time variables
129
- gzip (bool): Compress build context with gzip
130
131
Returns:
132
generator|list: Build output stream or list of build steps
133
"""
134
```
135
136
### Image Management
137
138
Local image operations including tagging, removal, and data export/import.
139
140
```python { .api }
141
def tag(image, repository, tag=None, force=False):
142
"""
143
Tag an image into a repository.
144
145
Parameters:
146
- image (str): Image name or ID to tag
147
- repository (str): Repository name for the tag
148
- tag (str): Tag name (default: 'latest')
149
- force (bool): Force tag creation
150
151
Returns:
152
bool: Success status
153
"""
154
155
def remove_image(image, force=False, noprune=False):
156
"""
157
Remove an image.
158
159
Parameters:
160
- image (str): Image name, ID, or tag
161
- force (bool): Force removal of image
162
- noprune (bool): Do not delete untagged parents
163
164
Returns:
165
list: List of deleted images and untagged references
166
"""
167
168
def get_image(image):
169
"""
170
Get an image as a tar archive.
171
172
Parameters:
173
- image (str): Image name, ID, or tag
174
175
Returns:
176
generator: Tar archive data stream
177
"""
178
179
def load_image(data):
180
"""
181
Load an image from tar archive data.
182
183
Parameters:
184
- data (bytes|file): Tar archive data or file-like object
185
186
Returns:
187
generator: Load output stream
188
"""
189
```
190
191
### Image Import Operations
192
193
Functions for importing images from various sources including tarballs, URLs, and other images.
194
195
```python { .api }
196
def import_image(src=None, repository=None, tag=None, image=None,
197
changes=None, stream_src=False):
198
"""
199
Import an image from a tarball or URL.
200
201
Parameters:
202
- src (str): Source URL or '-' for stdin
203
- repository (str): Repository name for imported image
204
- tag (str): Tag for imported image
205
- image (str): Image name (alternative to repository/tag)
206
- changes (list): List of Dockerfile-like changes to apply
207
- stream_src (bool): Treat src as stream data
208
209
Returns:
210
generator: Import output stream
211
"""
212
213
def import_image_from_data(data, repository=None, tag=None, changes=None):
214
"""
215
Import an image from raw data.
216
217
Parameters:
218
- data (bytes): Raw image data
219
- repository (str): Repository name
220
- tag (str): Tag name
221
- changes (list): Dockerfile-like changes
222
223
Returns:
224
generator: Import output stream
225
"""
226
227
def import_image_from_file(filename, repository=None, tag=None, changes=None):
228
"""
229
Import an image from a file.
230
231
Parameters:
232
- filename (str): Path to image file
233
- repository (str): Repository name
234
- tag (str): Tag name
235
- changes (list): Dockerfile-like changes
236
237
Returns:
238
generator: Import output stream
239
"""
240
241
def import_image_from_stream(stream, repository=None, tag=None, changes=None):
242
"""
243
Import an image from a stream.
244
245
Parameters:
246
- stream (file): File-like stream object
247
- repository (str): Repository name
248
- tag (str): Tag name
249
- changes (list): Dockerfile-like changes
250
251
Returns:
252
generator: Import output stream
253
"""
254
255
def import_image_from_url(url, repository=None, tag=None, changes=None):
256
"""
257
Import an image from a URL.
258
259
Parameters:
260
- url (str): URL to import from
261
- repository (str): Repository name
262
- tag (str): Tag name
263
- changes (list): Dockerfile-like changes
264
265
Returns:
266
generator: Import output stream
267
"""
268
269
def import_image_from_image(image, repository=None, tag=None, changes=None):
270
"""
271
Import from an existing image.
272
273
Parameters:
274
- image (str): Source image name or ID
275
- repository (str): Repository name
276
- tag (str): Tag name
277
- changes (list): Dockerfile-like changes
278
279
Returns:
280
generator: Import output stream
281
"""
282
```
283
284
### Deprecated Operations
285
286
Legacy image operations maintained for backwards compatibility.
287
288
```python { .api }
289
def insert(image, url, path):
290
"""
291
Insert a file into an image (deprecated for API < 1.12).
292
293
Parameters:
294
- image (str): Image name or ID
295
- url (str): URL to file to insert
296
- path (str): Path to insert file at
297
298
Returns:
299
dict: New image information
300
"""
301
```
302
303
## Authentication Configuration
304
305
Docker registry authentication is configured using auth_config dictionaries:
306
307
```python { .api }
308
# Auth config structure
309
auth_config = {
310
'username': 'your_username',
311
'password': 'your_password',
312
'email': 'your_email@example.com', # Optional
313
'serveraddress': 'https://index.docker.io/v1/', # Registry URL
314
'auth': 'base64_encoded_credentials' # Alternative to username/password
315
}
316
```
317
318
## Usage Examples
319
320
### Basic Image Operations
321
322
```python
323
import docker
324
325
client = docker.Client()
326
327
# Pull an image
328
for line in client.pull('ubuntu:20.04', stream=True, decode=True):
329
print(line.get('status', ''))
330
331
# List all images
332
images = client.images()
333
for image in images:
334
print(f"Repository: {image['RepoTags']}, Size: {image['Size']}")
335
336
# Inspect an image
337
image_info = client.inspect_image('ubuntu:20.04')
338
print(f"Architecture: {image_info['Architecture']}")
339
print(f"OS: {image_info['Os']}")
340
341
# Tag an image
342
client.tag('ubuntu:20.04', 'my-ubuntu', 'latest')
343
344
# Remove an image
345
client.remove_image('my-ubuntu:latest')
346
```
347
348
### Building Images
349
350
```python
351
# Build from Dockerfile in current directory
352
for line in client.build(path='.', tag='my-app:latest', stream=True, decode=True):
353
if 'stream' in line:
354
print(line['stream'].strip())
355
356
# Build with custom Dockerfile and build arguments
357
build_output = client.build(
358
path='/path/to/build/context',
359
dockerfile='Dockerfile.prod',
360
tag='my-app:production',
361
buildargs={
362
'BUILD_ENV': 'production',
363
'VERSION': '1.2.3'
364
},
365
pull=True,
366
nocache=True,
367
rm=True,
368
stream=True,
369
decode=True
370
)
371
372
for line in build_output:
373
if 'stream' in line:
374
print(line['stream'].strip())
375
```
376
377
### Working with Private Registries
378
379
```python
380
# Configure authentication
381
auth_config = {
382
'username': 'myuser',
383
'password': 'mypassword',
384
'serveraddress': 'registry.example.com'
385
}
386
387
# Pull from private registry
388
client.pull(
389
'registry.example.com/my-private-repo:latest',
390
auth_config=auth_config,
391
stream=True
392
)
393
394
# Push to private registry
395
client.tag('my-app:latest', 'registry.example.com/my-private-repo:v1.0')
396
397
for line in client.push(
398
'registry.example.com/my-private-repo:v1.0',
399
auth_config=auth_config,
400
stream=True,
401
decode=True
402
):
403
print(line.get('status', ''))
404
```
405
406
### Image Export and Import
407
408
```python
409
# Export image to tar file
410
with open('my-image.tar', 'wb') as f:
411
for chunk in client.get_image('my-app:latest'):
412
f.write(chunk)
413
414
# Load image from tar file
415
with open('my-image.tar', 'rb') as f:
416
client.load_image(f)
417
418
# Import image from tarball with modifications
419
changes = [
420
'ENV NEW_VAR=value',
421
'EXPOSE 8080'
422
]
423
424
client.import_image_from_file(
425
'exported-container.tar',
426
repository='imported-app',
427
tag='latest',
428
changes=changes
429
)
430
```
431
432
### Advanced Build Configuration
433
434
```python
435
# Build with resource limits
436
container_limits = {
437
'memory': 1024 * 1024 * 512, # 512MB
438
'memswap': 1024 * 1024 * 1024, # 1GB
439
'cpushares': 512,
440
'cpusetcpus': '0,1'
441
}
442
443
for line in client.build(
444
path='/build/context',
445
tag='resource-limited:latest',
446
container_limits=container_limits,
447
pull=True,
448
forcerm=True,
449
stream=True,
450
decode=True
451
):
452
if 'stream' in line:
453
print(line['stream'].strip())
454
```
455
456
### Image Search and Discovery
457
458
```python
459
# Search Docker Hub
460
search_results = client.search('nginx')
461
for result in search_results[:5]: # Show top 5 results
462
print(f"Name: {result['name']}")
463
print(f"Description: {result['description']}")
464
print(f"Stars: {result['star_count']}")
465
print(f"Official: {result['is_official']}")
466
print("---")
467
468
# Get image history
469
history = client.history('nginx:latest')
470
for layer in history:
471
print(f"Created: {layer['Created']}")
472
print(f"Size: {layer['Size']}")
473
print(f"Created by: {layer['CreatedBy'][:50]}...")
474
print("---")
475
```