蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测只读 docker images 五列结构、默认标签解析、Dockerfile 指令校验与 tag 共享语义

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-image-usage.py
explore-image-usage.py141 行
"""Offline verification lab for Docker Ch13: image-usage."""
import json
import shutil
import subprocess

DOCKER_BIN = shutil.which("docker") or r"C:\Program Files\Docker\Docker\resources\bin\docker.exe"
VERSION_LABEL = "Windows x64 / CPython 3.12.14 / Docker CLI 29.8.0 offline"


def run_docker(*args: str, timeout: int = 30) -> subprocess.CompletedProcess:
    return subprocess.run(
        [DOCKER_BIN, *args],
        capture_output=True,
        text=True,
        encoding="utf-8",
        timeout=timeout,
    )


def parse_image_ref(ref: str) -> tuple[str, str]:
    if ":" in ref.split("/")[-1]:
        repo, tag = ref.rsplit(":", 1)
        return repo, tag
    return ref, "latest"


def main() -> None:
    cases = []

    # Case 1: Read-only docker images listing & 5 standard columns check
    p_imgs = run_docker("images", "--format", "{{.Repository}}|{{.Tag}}|{{.ID}}|{{.CreatedSince}}|{{.Size}}")
    rows = [ln.split("|") for ln in p_imgs.stdout.strip().splitlines() if "|" in ln]
    repo_tags = {f"{r[0]}:{r[1]}" for r in rows if len(r) == 5}
    actual_ls = {
        "rc": p_imgs.returncode,
        "all_rows_5_cols": all(len(r) == 5 for r in rows) and len(rows) > 0,
        "cached_debian_and_nginx": {"debian:bookworm-slim", "nginx:1.27-alpine"}.issubset(repo_tags),
    }
    expected_ls = {"rc": 0, "all_rows_5_cols": True, "cached_debian_and_nginx": True}
    cases.append({
        "name": "list_local_images_and_columns",
        "summary": "Run read-only docker images and confirm 5 standard columns plus cached debian/nginx entries.",
        "expected": expected_ls,
        "actual": actual_ls,
        "passed": actual_ls == expected_ls,
    })

    # Case 2: REPOSITORY:TAG default-to-latest parser + pull/search/rmi CLI help
    parsed = {
        "bare": parse_image_ref("ubuntu"),
        "v15": parse_image_ref("ubuntu:15.10"),
        "v14": parse_image_ref("ubuntu:14.04"),
    }
    cli_ok = all(run_docker(c, "--help").returncode == 0 for c in ("pull", "search", "rmi"))
    actual_ref = {"parsed": parsed, "cli_help_ok": cli_ok}
    expected_ref = {
        "parsed": {"bare": ("ubuntu", "latest"), "v15": ("ubuntu", "15.10"), "v14": ("ubuntu", "14.04")},
        "cli_help_ok": True,
    }
    cases.append({
        "name": "image_ref_default_tag_parser",
        "summary": "Validate REPOSITORY:TAG default ':latest' resolution and docker pull/search/rmi CLI help.",
        "expected": expected_ref,
        "actual": actual_ref,
        "passed": actual_ref == expected_ref,
    })

    # Case 3: docker commit -m / -a flags & workflow check
    p_commit = run_docker("commit", "--help")
    actual_commit = {
        "rc": p_commit.returncode,
        "has_message_flag": "-m," in p_commit.stdout or "--message" in p_commit.stdout,
        "has_author_flag": "-a," in p_commit.stdout or "--author" in p_commit.stdout,
    }
    expected_commit = {"rc": 0, "has_message_flag": True, "has_author_flag": True}
    cases.append({
        "name": "commit_workflow_and_flags_check",
        "summary": "Verify docker commit supports -m/--message and -a/--author for committing container changes.",
        "expected": expected_commit,
        "actual": actual_commit,
        "passed": actual_commit == expected_commit,
    })

    # Case 4: Dockerfile instruction parser (uppercase directives, FROM first, layer steps) + docker build -t
    dockerfile_lines = [
        "FROM centos:6.7",
        'MAINTAINER Fisher "fisher@sudops.com"',
        "RUN /bin/echo 'root:123456' | chpasswd",
        "RUN useradd appuser",
        "RUN /bin/echo 'appuser:123456' | chpasswd",
        'RUN /bin/echo -e "LANG=\\"en_US.UTF-8\\"" > /etc/default/local',
        "EXPOSE 22",
        "EXPOSE 80",
        "CMD /usr/sbin/sshd -D",
    ]
    directives = [ln.split()[0] for ln in dockerfile_lines]
    p_build = run_docker("build", "--help")
    actual_df = {
        "first_directive": directives[0],
        "all_uppercase": all(d.isupper() for d in directives),
        "run_step_count": directives.count("RUN"),
        "build_has_tag_flag": p_build.returncode == 0 and "-t," in p_build.stdout,
    }
    expected_df = {
        "first_directive": "FROM",
        "all_uppercase": True,
        "run_step_count": 4,
        "build_has_tag_flag": True,
    }
    cases.append({
        "name": "dockerfile_instruction_parser_and_build_help",
        "summary": "Validate Dockerfile uppercase directives, FROM base step, RUN layers, and docker build -t flag.",
        "expected": expected_df,
        "actual": actual_df,
        "passed": actual_df == expected_df,
    })

    # Case 5: docker tag aliasing semantics & CLI help
    p_tag = run_docker("tag", "--help")
    tag_table = {"demo/centos:6.7": "860c279d2fec"}
    tag_table["demo/centos:dev"] = tag_table["demo/centos:6.7"]
    actual_tag = {
        "tag_help_ok": p_tag.returncode == 0,
        "same_image_id": tag_table["demo/centos:6.7"] == tag_table["demo/centos:dev"],
        "alias_count": len(tag_table),
    }
    expected_tag = {"tag_help_ok": True, "same_image_id": True, "alias_count": 2}
    cases.append({
        "name": "docker_tag_aliasing_and_help",
        "summary": "Verify docker tag CLI help and confirm adding a tag shares the exact same Image ID.",
        "expected": expected_tag,
        "actual": actual_tag,
        "passed": actual_tag == expected_tag,
    })

    print(json.dumps({"version": VERSION_LABEL, "cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/docker-image-usage-lab/explore-image-usage.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-image-usage.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Docker

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a1457.zip

下载课程关联工程包:Docker

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1466.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习