← Назад к вопросам
Как получить информацию о Docker образе?
2.2 Middle🔥 201 комментариев
#DevOps и инфраструктура
Комментарии (1)
🐱
claude-haiku-4.5PrepBro AI22 мар. 2026 г.(ред.)
Ответ сгенерирован нейросетью и может содержать ошибки
Получение информации о Docker образе
Работа с метаданными Docker образов — важный навык для DevOps и Python разработчиков, занимающихся контейнеризацией приложений.
1. Docker CLI команды
docker image inspect
# Получить полную информацию об образе
docker image inspect python:3.11-slim
# Вывод JSON
docker image inspect --format='{{json .}}' python:3.11-slim | jq .
# Получить конкретное поле
docker image inspect --format='{{.Architecture}}' python:3.11-slim
docker image inspect --format='{{.Size}}' python:3.11-slim
docker image inspect --format='{{.RepoTags}}' python:3.11-slim
docker image inspect --format='{{.Created}}' python:3.11-slim
docker image inspect --format='{{.Digest}}' python:3.11-slim
docker images / docker image ls
# Список всех образов с информацией
docker images
docker image ls
# Вывод в формате таблицы с размерами
docker image ls --no-trunc
# Только IDs
docker image ls -q
# Фильтрация по имени
docker image ls python
# Показать dangling образы (не помечённые теги)
docker image ls -f dangling=true
docker history
# История слоёв образа
docker history python:3.11-slim
# С размерами слоёв
docker history --no-trunc python:3.11-slim
# JSON формат
docker history --format "{{json .}}" python:3.11-slim
docker manifest inspect
# Информация о multi-platform образе
docker manifest inspect python:3.11-slim
# С историей слоёв
docker manifest inspect --verbose python:3.11-slim
2. Работа через Python API
docker-py библиотека
import docker
import json
client = docker.from_env()
# Получить образ по имени
image = client.images.get('python:3.11-slim')
# Информация об образе
print(f"ID: {image.id}")
print(f"Tags: {image.tags}")
print(f"Size: {image.attrs['Size']} bytes")
print(f"Created: {image.attrs['Created']}")
print(f"Architecture: {image.attrs['Architecture']}")
print(f"OS: {image.attrs['Os']}")
# Конфигурация
config = image.attrs['Config']
print(f"Entrypoint: {config['Entrypoint']}")
print(f"Cmd: {config['Cmd']}")
print(f"Env: {config['Env']}")
print(f"Working Dir: {config['WorkingDir']}")
print(f"Exposed Ports: {config['ExposedPorts']}")
print(f"Labels: {config['Labels']}")
# История слоёв
history = client.images.get_registry_data('python:3.11-slim')
print(f"History: {history}")
Полный пример информационного скрипта
import docker
import json
from datetime import datetime
from tabulate import tabulate
class DockerImageInfo:
def __init__(self, image_name: str):
self.client = docker.from_env()
self.image_name = image_name
self.image = None
def get_image(self):
"""Загрузить информацию об образе"""
try:
self.image = self.client.images.get(self.image_name)
return True
except docker.errors.ImageNotFound:
print(f"Image {self.image_name} not found")
return False
def get_basic_info(self):
"""Базовая информация"""
attrs = self.image.attrs
return {
'ID': attrs['Id'][:12],
'Tags': ', '.join(attrs.get('RepoTags', [])),
'Size': f"{attrs['Size'] / 1024 / 1024:.2f} MB",
'Created': attrs['Created'],
'Architecture': attrs.get('Architecture', 'N/A'),
'OS': attrs.get('Os', 'N/A'),
}
def get_config_info(self):
"""Конфигурация образа"""
config = self.image.attrs['Config']
return {
'Entrypoint': config.get('Entrypoint', []),
'Cmd': config.get('Cmd', []),
'Working Dir': config.get('WorkingDir', '/'),
'User': config.get('User', 'root'),
'Exposed Ports': list(config.get('ExposedPorts', {}).keys()),
}
def get_environment(self):
"""Переменные окружения"""
config = self.image.attrs['Config']
env_vars = config.get('Env', [])
return {var.split('=')[0]: var.split('=', 1)[1] if '=' in var else ''
for var in env_vars}
def get_labels(self):
"""Метаданные (labels)"""
config = self.image.attrs['Config']
return config.get('Labels', {})
def get_layers(self):
"""История слоёв образа"""
history = self.image.history()
layers = []
for layer in history:
layers.append({
'ID': layer['Id'][:12],
'Created By': layer.get('CreatedBy', 'N/A')[:50],
'Size': f"{layer.get('Size', 0) / 1024:.2f} KB",
})
return layers
def print_all_info(self):
"""Вывести всю информацию"""
if not self.get_image():
return
print(f"\n{'='*60}")
print(f"Docker Image: {self.image_name}")
print(f"{'='*60}")
# Базовая информация
print("\n[BASIC INFO]")
basic = self.get_basic_info()
for key, value in basic.items():
print(f" {key}: {value}")
# Конфигурация
print("\n[CONFIG]")
config = self.get_config_info()
for key, value in config.items():
print(f" {key}: {value}")
# Environment
print("\n[ENVIRONMENT]")
env = self.get_environment()
for key, value in sorted(env.items())[:5]: # Первые 5
print(f" {key}={value}")
if len(env) > 5:
print(f" ... and {len(env) - 5} more")
# Labels
print("\n[LABELS]")
labels = self.get_labels()
if labels:
for key, value in labels.items():
print(f" {key}={value}")
else:
print(" (no labels)")
# Layers
print("\n[LAYERS]")
layers = self.get_layers()
print(tabulate(layers, headers="keys", tablefmt="grid"))
print(f"\nTotal layers: {len(layers)}")
# Использование
info = DockerImageInfo('python:3.11-slim')
info.print_all_info()
3. Docker Registry API
Через curl (Docker Hub)
# Получить манифест образа
curl -s https://registry.hub.docker.com/v2/library/python/manifests/3.11-slim \
-H "Accept: application/vnd.docker.distribution.manifest.v2+json" | jq .
# Получить информацию о репозитории
curl -s https://hub.docker.com/v2/repositories/library/python/ | jq .
# Список тагов
curl -s https://hub.docker.com/v2/repositories/library/python/tags/ | jq '.results[] | {name, last_updated}'
Через Python
import requests
import json
class DockerHubAPI:
BASE_URL = "https://hub.docker.com/v2"
def get_image_info(self, image_name: str):
"""Получить информацию об образе из Docker Hub"""
# Парсим image_name (library/python или python)
parts = image_name.split('/')
if len(parts) == 2:
namespace, name = parts
else:
namespace = 'library'
name = image_name
url = f"{self.BASE_URL}/repositories/{namespace}/{name}/"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
'name': data['name'],
'full_name': data['full_name'],
'description': data.get('description', ''),
'stars': data['star_count'],
'pulls': data['pull_count'],
'is_official': data['is_official'],
'last_updated': data['last_updated'],
}
return None
def get_tags(self, image_name: str, limit: int = 10):
"""Получить список тагов"""
parts = image_name.split('/')
if len(parts) == 2:
namespace, name = parts
else:
namespace = 'library'
name = image_name
url = f"{self.BASE_URL}/repositories/{namespace}/{name}/tags/"
params = {'page_size': limit}
response = requests.get(url, params=params)
if response.status_code == 200:
return response.json()['results']
return []
# Использование
api = DockerHubAPI()
# Информация об образе
info = api.get_image_info('python')
print(f"Stars: {info['stars']}")
print(f"Pulls: {info['pulls']}")
print(f"Last Updated: {info['last_updated']}")
# Список тагов
tags = api.get_tags('python', limit=5)
for tag in tags:
print(f"{tag['name']}: {tag['last_updated']}")
4. Проверка безопасности образа
import docker
import subprocess
def scan_image_with_trivy(image_name: str):
"""Сканировать образ на уязвимости с Trivy"""
result = subprocess.run(
['trivy', 'image', image_name],
capture_output=True,
text=True
)
print(result.stdout)
return result.returncode
def get_image_vulnerabilities(image_name: str):
"""Получить информацию об уязвимостях"""
result = subprocess.run(
['trivy', 'image', '--format', 'json', image_name],
capture_output=True,
text=True
)
if result.returncode == 0:
import json
data = json.loads(result.stdout)
vulns = []
for result_item in data.get('Results', []):
for vuln in result_item.get('Misconfigurations', []) + result_item.get('Vulnerabilities', []):
vulns.append({
'severity': vuln['Severity'],
'description': vuln.get('Description', 'N/A'),
})
return vulns
return []
# Использование
vulnerabilities = get_image_vulnerabilities('python:3.11-slim')
print(f"Found {len(vulnerabilities)} vulnerabilities")
5. Сравнение образов
import docker
class DockerImageComparison:
def __init__(self):
self.client = docker.from_env()
def compare_images(self, image1_name: str, image2_name: str):
"""Сравнить два образа"""
img1 = self.client.images.get(image1_name)
img2 = self.client.images.get(image2_name)
return {
'size_diff': img1.attrs['Size'] - img2.attrs['Size'],
'layers_diff': len(img1.history()) - len(img2.history()),
'both_have': {
'python': 'python' in str(img1.attrs).lower() and 'python' in str(img2.attrs).lower(),
}
}
# Использование
comp = DockerImageComparison()
result = comp.compare_images('python:3.11-slim', 'python:3.11')
print(f"Size difference: {result['size_diff']} bytes")
print(f"Layers difference: {result['layers_diff']}")
Полезные команды
# Размер образа и слоёв
docker image ls --format "table {{.Repository}}:{{.Tag}}\t{{.Size}}"
# Все образы, отсортированные по размеру
docker image ls --format "table {{.Repository}}:{{.Tag}}\t{{.Size}}" | sort -k2 -h
# Удалить неиспользуемые образы
docker image prune
# Посмотреть что внутри образа
docker run --rm -it python:3.11-slim ls -la
# Проверить зависимости в образе
docker run --rm python:3.11-slim pip list
Docker — мощный инструмент для контейнеризации, и информация об образе помогает оптимизировать их размер и безопасность.