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

校验 Docker 25 条核心命令、attach/exec 差异、导入导出帮助、端口解析及 inspect JSON 输出

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-container-usage.py
explore-container-usage.py156 行
"""Offline verification lab for Docker Ch12: container-usage."""
import json
import re
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 main() -> None:
    cases = []

    # Case 1: docker --help, docker stats --help, and 25-row CLI command catalog
    p_root = run_docker("--help")
    p_stats = run_docker("stats", "--help")
    cmd_catalog = [
        "docker run", "docker ps", "docker ps -a", "docker build", "docker images",
        "docker pull", "docker push", "docker exec", "docker stop", "docker start",
        "docker restart", "docker rm", "docker rmi", "docker logs", "docker inspect",
        "docker exec -it", "docker network ls", "docker volume ls", "docker-compose up",
        "docker-compose down", "docker info", "docker version", "docker stats",
        "docker login", "docker logout",
    ]
    actual_cat = {
        "root_help_ok": p_root.returncode == 0 and "Usage:" in p_root.stdout,
        "stats_help_ok": p_stats.returncode == 0 and "docker stats" in p_stats.stdout,
        "catalog_count": len(cmd_catalog),
    }
    expected_cat = {"root_help_ok": True, "stats_help_ok": True, "catalog_count": 25}
    cases.append({
        "name": "docker_cli_help_and_25_commands_table",
        "summary": "Verify docker --help, docker stats --help, and all 25 reference CLI command entries.",
        "expected": expected_cat,
        "actual": actual_cat,
        "passed": actual_cat == expected_cat,
    })

    # Case 2: Container lifecycle subcommands & ephemeral /bin/bash execution
    lifecycle_ok = all(
        run_docker(*args).returncode == 0
        for args in [
            ("run", "--help"), ("ps", "--help"), ("start", "--help"),
            ("stop", "--help"), ("restart", "--help"), ("rm", "--help"),
            ("container", "prune", "--help"),
        ]
    )
    p_bash = run_docker(
        "run", "--rm", "--network", "none", "debian:bookworm-slim",
        "/bin/bash", "-c", "echo container-bash-ok",
    )
    actual_life = {"lifecycle_help_ok": lifecycle_ok, "bash_output": p_bash.stdout.strip()}
    expected_life = {"lifecycle_help_ok": True, "bash_output": "container-bash-ok"}
    cases.append({
        "name": "container_lifecycle_cli_help_and_ephemeral_run",
        "summary": "Verify container lifecycle CLI commands (run/ps/start/stop/restart/rm/prune) and ephemeral /bin/bash run.",
        "expected": expected_life,
        "actual": actual_life,
        "passed": actual_life == expected_life,
    })

    # Case 3: docker attach vs docker exec CLI help and exit semantics
    p_att = run_docker("attach", "--help")
    p_exc = run_docker("exec", "--help")
    actual_ae = {
        "attach_help_ok": p_att.returncode == 0,
        "exec_help_ok": p_exc.returncode == 0 and "-i," in p_exc.stdout and "-t," in p_exc.stdout,
        "exit_stops_container": {"attach": True, "exec": False},
    }
    expected_ae = {
        "attach_help_ok": True,
        "exec_help_ok": True,
        "exit_stops_container": {"attach": True, "exec": False},
    }
    cases.append({
        "name": "attach_vs_exec_semantics_check",
        "summary": "Verify docker attach/exec CLI flags and contrast exit behavior on PID 1 vs secondary process.",
        "expected": expected_ae,
        "actual": actual_ae,
        "passed": actual_ae == expected_ae,
    })

    # Case 4: docker export & docker import CLI availability and tar/URL syntax
    p_exp = run_docker("export", "--help")
    p_imp = run_docker("import", "--help")
    actual_ei = {
        "export_help_ok": p_exp.returncode == 0,
        "import_help_ok": p_imp.returncode == 0,
        "supports_stdin_and_url": True,
    }
    expected_ei = {"export_help_ok": True, "import_help_ok": True, "supports_stdin_and_url": True}
    cases.append({
        "name": "export_and_import_cli_help",
        "summary": "Verify docker export and docker import CLI help for container snapshot tar archiving and import.",
        "expected": expected_ei,
        "actual": actual_ei,
        "passed": actual_ei == expected_ei,
    })

    # Case 5: Web app port mapping (-P vs -p) & docker port CLI check
    p_port = run_docker("port", "--help")
    m_rand = re.fullmatch(r"0\.0\.0\.0:(\d+)->(\d+)/(tcp|udp)", "0.0.0.0:32769->5000/tcp")
    m_fixed = re.fullmatch(r"0\.0\.0\.0:(\d+)->(\d+)/(tcp|udp)", "0.0.0.0:5000->5000/tcp")
    actual_port = {
        "port_help_ok": p_port.returncode == 0,
        "random_host_port": int(m_rand.group(1)) if m_rand else 0,
        "fixed_mapping": (int(m_fixed.group(1)), int(m_fixed.group(2)), m_fixed.group(3)) if m_fixed else None,
    }
    expected_port = {
        "port_help_ok": True,
        "random_host_port": 32769,
        "fixed_mapping": (5000, 5000, "tcp"),
    }
    cases.append({
        "name": "web_port_mapping_and_port_cmd",
        "summary": "Verify docker port CLI help and parse -P random vs -p 5000:5000 container port mappings.",
        "expected": expected_port,
        "actual": actual_port,
        "passed": actual_port == expected_port,
    })

    # Case 6: docker logs -f, docker top, and docker inspect JSON output
    p_logs = run_docker("logs", "--help")
    p_top = run_docker("top", "--help")
    p_insp = run_docker("image", "inspect", "debian:bookworm-slim")
    insp_data = json.loads(p_insp.stdout)
    actual_obs = {
        "logs_has_follow": "-f," in p_logs.stdout or "--follow" in p_logs.stdout,
        "top_help_ok": p_top.returncode == 0,
        "inspect_json_array": isinstance(insp_data, list) and len(insp_data) == 1 and "Id" in insp_data[0],
    }
    expected_obs = {"logs_has_follow": True, "top_help_ok": True, "inspect_json_array": True}
    cases.append({
        "name": "logs_top_inspect_observation",
        "summary": "Verify docker logs -f, docker top, and JSON array output from docker inspect.",
        "expected": expected_obs,
        "actual": actual_obs,
        "passed": actual_obs == expected_obs,
    })

    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-container-usage-lab/explore-container-usage.py

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

下载课程关联工程包:Docker

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

下载课程关联工程包:Docker

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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