Docker Image Management

Images are the core building blocks of Docker—mastering image management means mastering the "software repository" of the container world.

1. What You'll Learn


2. A True Story of an Operations Engineer

(1) Pain Point: CI Server Disk Alert

Bob received a disk alert from the CI server—Docker images were taking up 40 GB of space. Upon investigation, he found a large number of <none> orphaned images (leftovers from old builds) and five versions of Node.js images (1.2 GB each), even though the team actually only needed the two most recent versions. The disk was 80% full, and builds began to fail.

(2) Solution for Mirror Cleanup

Bob deleted 20 GB of unused images with just three commands.

BASH
# Remove dangling images (untagged leftovers)
docker image prune -f

# Remove images not used by any container
docker image prune -a -f

# Check disk usage after cleanup
docker system df

(3) Benefit: Recovered disk space

20 GB of space was freed up, disk usage dropped from 80% to 35%, and CI builds resumed normal operation.


3. Images and Docker Hub

(1) Components of an Image

A Docker image is composed of multiple read-only layers stacked on top of one another, with each layer representing a change to the file system.

100%
graph TB
    L4["CMD ['nginx', '-g', 'daemon off;']<br/>Startup Command"]
    L3["COPY html /usr/share/nginx/html<br/>Application Code"]
    L2["RUN apt-get install nginx<br/>Install the software"]
    L1["FROM debian:bookworm-slim<br/>Basic System"]
    L4 --> L3 --> L2 --> L1

(2) Image Naming Conventions

TEXT
registry/repository:tag
Component Description Example
registry Repository URL (Docker Hub by default) docker.io / localhost:5000
repository Repository Name (User/Image Name) library/nginx / myorg/myapp
tag Version tag (default: latest) 1.25-alpine / latest / v2.0

(3) Common Tag Naming Conventions

Tag Suffix Meaning Size Reference Use Cases
latest Default Latest Version Maximum Quick Trial
alpine Alpine Linux Basics Minimal (5–50 MB) Production/Resource-Constrained
slim Minimal Debian Small (80–150 MB) Production (requires glibc)
bookworm / jammy Specify Debian/Ubuntu version Medium (100–300 MB) Requires specific system libraries
v1.25.3 Exact version number Depends on the base image Production-locked version

4. Basic Operations with Images

▶ Example: Pulling Nginx images with different tags (Difficulty: ⭐)

BASH
# Pull nginx with different tags
docker pull nginx:latest
docker pull nginx:1.25-alpine
docker pull nginx:1.25

# View pulled images
docker images
💻 Output:

TEXT
REPOSITORY   TAG            SIZE
nginx        latest         187MB
nginx        1.25-alpine    42.5MB
nginx        1.25           187MB
💡 Tip: Different tags of the same base image share the same underlying data, so the actual storage usage is much less than the sum of the sizes of the three images (deduplicated storage).

▶ Example: Viewing the list of local images (Difficulty: ⭐)

BASH
# List all local images
docker images

# Filter by repository name
docker images nginx

# Show only image IDs
docker images -q

▶ Example: Tagging an image (docker tag) (Difficulty: ⭐⭐)

BASH
# Tag an existing image for a private registry
docker tag nginx:1.25-alpine localhost:5000/myapp/nginx:v1

# Verify the new tag
docker images | grep myapp
💻 Output:

TEXT
localhost:5000/myapp/nginx   v1       42.5MB
📌 Key Point: docker tag Does not create a copy of the image; it only creates an alias pointing to the same image. The two tags share storage and do not take up any additional space.

▶ Example: Deleting an image (Difficulty: ⭐⭐)

BASH
# Remove an image by name:tag
docker rmi nginx:1.25

# Remove by image ID
docker rmi a1b2c3d4e5f6

# Force remove (even if used by stopped containers)
docker rmi -f nginx:latest
⚠️ Note: An image cannot be deleted while it is being used by a running container. You must first docker stop + docker rm the container before deleting the image.

▶ Example: Checking disk usage (Difficulty: ⭐)

BASH
# Show Docker disk usage breakdown
docker system df

# Show detailed per-image size
docker system df -v
💻 Output:

TEXT
TYPE            TOTAL   ACTIVE  SIZE      RECLAIMABLE
Images          5       2       1.2GB     800MB (66%)
Containers      3       1       150MB     120MB (80%)
Local Volumes   2       1       500MB     250MB (50%)
Build Cache     10      0       300MB     300MB (100%)

5. Mirror Layering and Caching

(1) The Principle of Stratification

Each Dockerfile instruction generates an image layer. During docker pull, layers are downloaded one by one, and existing layers are skipped.

100%
graph TB
    subgraph "Image Layers (Shared, Read-only)"
        L1["Layer 1: Base OS<br/>debian:bookworm-slim"]
        L2["Layer 2: apt install<br/>nginx + deps"]
        L3["Layer 3: COPY html<br/>Custom content"]
    end
    subgraph "Container Layer (Writable)"
        C["Container Layer<br/>Runtime changes<br/>logs, temp files"]
    end
    C --> L3 --> L2 --> L1

(2) Benefits of Layering

Benefits Description
Storage Deduplication Only one copy is stored per tier; multiple images share it
Transfer Acceleration Skips existing layers during a pull and downloads only new layers
Build Acceleration Unchanged layers use the cache; they are not rebuilt

(3) View the image build history

BASH
# Show image build history (each layer)
docker history nginx:1.25-alpine
💻 Output (excerpt):

TEXT
IMAGE          CREATED       CREATED BY                                      SIZE
e1ade32        2 weeks ago   CMD ["nginx" "-g" "daemon off;"]                0B
<missing>      2 weeks ago   STOPSIGNAL SIGQUIT                              0B
<missing>      2 weeks ago   ENTRYPOINT ["/docker-entrypoint.sh"]            0B
<missing>      2 weeks ago   COPY 15-local-resolvers.envsh /etc...           389B
<missing>      2 weeks ago   COPY 30-tune-worker-processes.sh /etc...        4.61kB
<missing>      2 weeks ago   RUN /bin/sh -c set -x ... && apk add...         30.4MB
<missing>      2 months ago  /bin/sh -c #(nop)  CMD ["/bin/sh"]              0B

6. Mirror Cleanup Policy

(1) Comparison of Three Cleanup Commands

Command Scope of Cleanup Risk Applicable Scenarios
docker rmi <image> Delete Specified Image Low (Precise Control) Delete Known Unwanted Images
docker image prune Delete orphaned mirror (<none> tag) Very low (no references) Routine cleanup
docker image prune -a Delete all images not used by containers Medium (may delete some that are still needed) When disk space is low
docker system prune Clean up everything (images + containers + volumes + cache) High (extensive deletion) Comprehensive cleanup

▶ Example: Cleaning Up Orphaned Images (Difficulty: ⭐)

BASH
# Remove dangling (untagged) images
docker image prune -f
💻 Output:

TEXT
Deleted Images:
untagged: <none>
deleted: sha256:a1b2c3d4...
Total reclaimed space: 150MB

(2) Comparison of Common Base Image Sizes

Mirror Size Package Manager Features
alpine:3.19 7 MB apk Minimal,musl libc
debian:bookworm-slim 74 MB apt Standard glibc, good compatibility
ubuntu:22.04 77 MB apt Rich ecosystem
node:20-alpine 135 MB apk + npm Node.js runtime
python:3.12-slim 155 MB apt + pip Python runtime
golang:1.22 780 MB apt + go Compile environment

7. Complete Example: Pull Image → Tag → Push → Clean Up

BASH
# ============================================
# Complete walkthrough: Image lifecycle management
# Covers: pull, tag, push (local registry), clean
# ============================================

# 1. Pull nginx Alpine image
docker pull nginx:1.25-alpine

# 2. View image details
docker images nginx
docker history nginx:1.25-alpine

# 3. Tag for a local registry
docker tag nginx:1.25-alpine localhost:5000/web/nginx:v1.0

# 4. Start a local registry (for push target)
docker run -d -p 5000:5000 --name registry registry:2

# 5. Push the tagged image to local registry
docker push localhost:5000/web/nginx:v1.0

# 6. Verify the push
curl -s http://localhost:5000/v2/web/nginx/tags/list | python3 -m json.tool

# 7. Remove local copies
docker rmi localhost:5000/web/nginx:v1.0

# 8. Pull back from local registry to verify
docker pull localhost:5000/web/nginx:v1.0

# 9. Clean up: stop registry and remove all unused images
docker stop registry && docker rm registry
docker image prune -a -f

# 10. Check final disk usage
docker system df
💻 Output (excerpt):

TEXT
# docker push localhost:5000/web/nginx:v1.0
The push refers to repository [localhost:5000/web/nginx]
5f0e3b...: Pushed
latest: digest: sha256:7be1... size: 1361

# curl http://localhost:5000/v2/web/nginx/tags/list
{"name":"web/nginx","tags":["v1.0"]}

# docker system df
TYPE            TOTAL   ACTIVE  SIZE      RECLAIMABLE
Images          1       0       42.5MB    42.5MB (100%)

❓ FAQ

Q Does the :latest tag update automatically?
A No. Existing local :latest tags will not update automatically. You must explicitly use docker pull nginx:latest to retrieve the latest version. In production environments, avoid using :latest; instead, use an exact version number (such as nginx:1.25.4) to ensure reproducibility.
Q What is the difference between the Alpine and Slim images?
A Alpine is based on musl libc and BusyBox; it is extremely small (7 MB) but may have compatibility issues (such as with Python C extensions). Slim is based on Debian and uses glibc; it offers good compatibility but is larger (80–150 MB). Use Slim whenever possible, and use Alpine only when disk space is extremely limited.
Q What is a dangling image?
A An unlabeled image (displayed as <none>:<none>) is typically created when a new build overwrites an old image—the old image loses its label but its layers remain. Use docker image prune to safely clean it up; this will not affect any images currently in use.
Q How do I view an image's build history?
A docker history <image> displays the size, creation time, and corresponding Dockerfile instructions for each layer. Add --no-trunc to view the full commands. This is a key tool for analyzing image size and optimizing the Dockerfile.
Q How do I set up a private repository?
A The easiest way is to use docker run -d -p 5000:5000 registry:2, which lets you set up a local registry in under 5 seconds. For production environments, we recommend using Harbor (which includes a web UI, authentication, and image scanning) or a cloud provider’s container registry (such as AWS ECR or Alibaba Cloud ACR).
Q Why isn’t the space freed up after deleting an image?
A Docker uses OverlayFS for layered storage, and multiple images may share the same base layers. Deleting an image only frees up the layers it exclusively uses. Use docker system df -v to view the actual recoverable space for each image.

📖 Summary


📝 Exercises

  1. Basic Exercise (Difficulty ⭐): Pull three Ubuntu images with different tags from Docker Hub (latest / 22.04 / 20.04), and compare their sizes using docker images.
  2. Advanced Question (Difficulty ⭐⭐): Use docker history nginx:latest to analyze the layers of the Nginx image, identify the largest layer, and explain what operation it corresponds to.
  3. Challenge (Difficulty: ⭐⭐⭐): Run docker system df -v to analyze the disk usage distribution of Docker on your local machine, then execute docker image prune -a -f to clean it up, and compare how much space was reclaimed before and after the cleanup.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏