Другое

Как проверить содержимое Docker‑образа после pull‑а и узнать детали

Узнайте, как просмотреть файлы, каталоги и ПО внутри Docker‑образа без запуска контейнера, используя временные контейнеры, извлечение слоёв и инструменты.

Как просмотреть содержимое Docker‑образа после его скачивания?

Я успешно скачал Docker‑образ и могу вывести его список с помощью команд Docker. Однако мне нужно увидеть фактическое содержимое этого образа, чтобы понять, какие файлы, каталоги и программное обеспечение в нём находятся. Несмотря на поиск в интернете, я не нашёл простого, понятного способа просмотреть содержимое Docker‑образа. Какие лучшие подходы или команды можно использовать для изучения содержимого Docker‑образа?

You can inspect Docker image contents by running a temporary container from the image, using docker run -it --rm image-name /bin/bash to access a shell inside the container, or by extracting the image layers with docker save image-name | tar -t to view the filesystem structure without running the container. Another effective method is to use docker export <container-id> | tar -t after starting a temporary container, or leverage specialized tools like docker-image-explorer and dive for more comprehensive analysis of image layers and contents.

Contents


Running a Temporary Container for Inspection

The most straightforward method to inspect a Docker image’s contents is to run a temporary container from the image and explore its filesystem. This approach gives you full access to the image’s filesystem as it would appear when the container is running.

Basic Command Structure

bash
docker run -it --rm <image-name> /bin/bash
  • -i keeps STDIN open for interactive use
  • -t allocates a pseudo-TTY
  • --rm automatically removes the container when you exit
  • /bin/bash starts an interactive shell

Alternative Shell Options

If the image doesn’t have /bin/bash, you can try:

bash
docker run -it --rm <image-name> /bin/sh
docker run -it --rm <image-name> ash
docker run -it --rm <image-name> zsh

Practical Example

bash
# Start a temporary Ubuntu container
docker run -it --rm ubuntu:latest /bin/bash

# Inside the container, explore contents
ls -la /          # List root directory contents
find / -type f -name "*.conf" 2>/dev/null  # Find configuration files
ls -la /usr/bin   # List binary executables
cat /etc/os-release  # View OS information

This method provides the most accurate representation of what you’ll actually find when containers run from this image, as it shows the exact filesystem state after all startup scripts have executed.


Using Docker Exec to Explore Container Contents

If you need to inspect an image while also running actual workloads, you can start a container in detached mode and then use docker exec to explore its contents interactively.

Starting and Exploring a Container

bash
# Start container in detached mode
docker run -d --name <container-name> <image-name>

# Execute shell in the running container
docker exec -it <container-name> /bin/bash

# Explore contents (same commands as above)
ls -la /usr/local/bin
find /etc -name "*.d" -type d
cat /var/log/dmesg | head -10

# Clean up
docker stop <container-name>
docker rm <container-name>

Useful Docker Exec Commands

bash
# List files without opening shell
docker exec <container-name> ls -la /opt

# Check specific directories
docker exec <container-name> find /var -name "*.log" -mtime -7

# View file contents
docker exec <container-name> cat /etc/passwd | head -5

# Check disk usage
docker exec <container-name> df -h

The docker exec approach is particularly useful when you need to verify that applications are properly installed and configured within the image, as it allows you to inspect the container while it’s actually running services.


Extracting and Inspecting Image Layers

Docker images consist of multiple layers, and you can inspect these layers individually to understand how the image was constructed and what files were added in each step.

Finding Image Layers

bash
# Get image ID
docker images <image-name>

# Inspect image layers
docker history <image-name>

Extracting Specific Layers

bash
# Get layer IDs
docker history <image-name> --no-trunc | grep -v '<missing>'

# Extract a specific layer
docker save <image-name> | tar -x --to-stdout <layer-id>/layer.tar | tar -t

Layer Analysis Commands

bash
# Show all files in all layers
docker save <image-name> | tar -t | grep -v '^[^/]*$'

# Count files per layer
docker history <image-name> --format "{{.CreatedBy}} {{.Size}}" | while read line; do
  echo "Layer: $line"
  docker save <image-name> | tar -x --to-stdout "${line%% *}/layer.tar" | tar -t | wc -l
done

Layer inspection is particularly valuable for understanding image size optimization, identifying where specific files were added, and debugging image build issues. Each layer represents a change from the previous layer, showing exactly what was modified, added, or removed.


Using Docker Save and Tar Extraction

The docker save command allows you to export an image as a tar archive, which you can then extract and inspect locally without needing Docker to be running.

Exporting the Image

bash
# Save image to tar file
docker save <image-name> -o image.tar

Extracting and Inspecting the Tar Archive

bash
# Extract the tar file
mkdir -p extracted-image
tar -xvf image.tar -C extracted-image

# Explore the extracted structure
cd extracted-image
ls -la

Analyzing Image Contents

bash
# View manifest
cat manifest.json | jq .

# Explore layer contents
find . -name "*.tar" -exec sh -c '
  echo "=== Layer: $(basename {}) ==="
  tar -tf "{}" | head -20
' \;

# Extract specific layers for detailed inspection
mkdir -p layers
find . -name "*.tar" -exec sh -c '
  layer_name=$(basename "{}" .tar)
  mkdir -p "layers/$layer_name"
  tar -xf "{}" -C "layers/$layer_name"
' \;

# Inspect extracted layers
ls -la layers/

This method provides a complete offline copy of the image that you can analyze thoroughly, making it ideal for security audits, compliance checks, or when you need to share image contents with others who don’t have access to the Docker registry.


Third-Party Tools for Image Inspection

Several specialized tools have been developed specifically for Docker image inspection, offering more advanced features than basic command-line methods.

Dive - Interactive Image Inspector

bash
# Install dive
curl -L https://github.com/wagoodman/dive/releases/latest/download/dive_$(uname -s)_$(uname -m).tar.gz | tar -xz
sudo install dive /usr/local/bin

# Use dive to inspect image
dive <image-name>

Dive provides an interactive interface showing:

  • Layer-by-layer filesystem changes
  • File contents and metadata
  • Size analysis and optimization suggestions
  • Visual diff between layers

Docker Image Explorer

bash
# Install docker-image-explorer
go install github.com/containers/dive@latest

# Use the tool
dive <image-name>

Other Useful Tools

bash
# ImageLayers - Visual layer inspection
docker run --rm -it \
  -v /var/run/docker.sock:/var/run/docker.sock \
  stefanprodan/imagediff

# Whalesay - Quick image inspection
docker run --rm -it \
  -v /var/run/docker.sock:/var/run/docker.sock \
  whalesay inspect <image-name>

These tools provide comprehensive analysis capabilities, including visual representations of image layers, duplicate file detection, and optimization recommendations. They’re particularly valuable for DevOps teams managing large numbers of container images.


Best Practices and Security Considerations

When inspecting Docker image contents, it’s important to follow security best practices and consider the implications of different inspection methods.

Security Considerations

bash
# Run inspection containers with minimal privileges
docker run --read-only --tmpfs /tmp:exec --cap-drop ALL <image-name> /bin/bash

# Use anonymous user IDs when inspecting
docker run -u nobody <image-name> /bin/bash

# Limit network access during inspection
docker run --network none <image-name> /bin/bash

Production Inspection Guidelines

  1. Use dedicated inspection containers - Never inspect images on production systems
  2. Clean up temporary containers - Always use --rm flag when possible
  3. Minimal privilege execution - Run inspection commands with least privilege
  4. Log inspection activities - Keep audit trails of image inspections
  5. Validate image integrity - Check image digests and signatures

Performance Optimization Tips

bash
# Cache layer inspection results
docker history <image-name> --format "{{.CreatedBy}}" > layer_commands.txt

# Batch file operations
docker exec <container-name> find / -name "*.so" -exec ls -la {} \;

# Use efficient file system tools
docker exec <container-name> find /usr -type f -mtime -1 -exec stat -c "%y %n" {} \;

Compliance and Auditing

For organizations subject to compliance requirements, consider:

bash
# Generate detailed inspection reports
docker inspect <image-name> --format '{
  "Id": {{.Id}},
  "Created": {{.Created}},
  "Labels": {{.Config.Labels}},
  "Env": {{.Config.Env}},
  "ExposedPorts": {{.Config.ExposedPorts}},
  "Volumes": {{.Config.Volumes}}
}' > image_report.json

# Check for sensitive data
docker exec <container-name> grep -r "password\|secret\|key" /etc /opt /usr/local 2>/dev/null

Following these practices ensures that your image inspection processes are secure, efficient, and compliant with organizational and regulatory requirements.


Sources

  1. Official Docker Documentation - Inspect Images
  2. Docker Run Reference
  3. Docker Save Command
  4. Dive - Interactive Docker Image Inspector
  5. Docker Best Practices - Image Security
  6. Container Security - Image Analysis
  7. Docker History Command

Conclusion

Inspecting Docker image contents is essential for understanding what’s inside your containers, verifying deployments, and troubleshooting issues. The most effective approach is to run a temporary container with docker run -it --rm image-name /bin/bash for interactive exploration, or use docker exec with running containers for real-time inspection. For deeper analysis, extract image layers with docker save or use specialized tools like dive for comprehensive layer-by-layer examination. Always follow security best practices by using minimal privileges, cleaning up temporary containers, and logging inspection activities. These methods will give you complete visibility into your Docker image contents while maintaining security and compliance standards.

Авторы
Проверено модерацией
Модерация