Skip to content
TheChatArchiveThe Chat Archive
GPT 5.1· openaiHugging Face Frontier Reasoning Traces

Build a Python tool to manage Docker containers with the Docker SDK.

  1. User

    Build a Python tool to manage Docker containers with the Docker SDK.

  2. Assistant

    Creating a Docker management tool

    I'm thinking about proposing a CLI tool file called docker_manager.py that uses argparse for simplicity. I could suggest sample usage like python docker_manager.py list or python docker_manager.py run --image nginx -d -p 8080:80. Although libraries like Typer and Click improve the user experience, I think using argparse keeps it dependency-free. I should also mention installing the Docker SDK with pip install docker. The user likely wants a functional script and a thorough explanation, so I'll detail the requirements and necessary functions.Planning run command options

    For the "run" command, I should include several options: a positional image argument, an optional name, an optional command, a detach flag (-d), and port mapping (-p) to allow multiple mappings. The same goes for environment variables (-e) which I'll need to parse into a dictionary. Minimal error handling could come from try/except blocks for Docker exceptions. I’ll organize the code logically, starting with the necessary imports and a function to get the Docker client. I wonder if I should stick with the high-level DockerClient since it's typically sufficient.Implementing container management functions

    I’m outlining functions for the CLI tool. First, the list_containers function retrieves all containers and prints their details, including short ID, name, status, and image tags. Then, for run_container, I’ll parse ports and environment variables based on user input and use the Docker client to run the container with provided arguments.

    For stopping, starting, and removing containers, I’ll create simple functions, and for logs, I’ll set it up to follow the output if requested.

    Finally, I'll implement a parse_ports function to manage port mappings, which simplifies how we handle multiple entries.Ensuring bug-free code

    I want to make sure the code stays bug-free. I should consider edge cases, such as handling invalid mapping strings by catching ValueError and displaying appropriate messages. I’ll create a main() function to set up the argument parser and subparsers.

    In my argparse design, I’ll ensure that the subcommands are linked to their respective functions. It’s important to check the Docker environment variables, but using from_env covers that. Finally, I should clarify that users need to install the Docker SDK and run the tool in an environment where the Docker engine is accessible.Finalizing Docker container management tool

    I need to address user permissions on Linux, like adding users to the docker group or using sudo. I’m proposing the filename docker_tool.py and might suggest minimal unit tests or ways to extend functionality. I’ll also check the Docker SDK API to ensure proper implementation, especially around handling the run() method and logs.

    I will create a main function for argument parsing and link it to the corresponding container functions, ensuring error handling, particularly for Docker exceptions. It’s important to clarify that this tool is less feature-rich than the Docker CLI but serves as a useful base for managing containers.Implementing Docker container management

    I'm designing a function to parse port mappings from host to container, defaulting to TCP. The key is to format the mapping correctly to create a dictionary for easy accessibility. I'll implement error handling for invalid mappings.

    Next, I'll structure the argument parsers for the various commands like list, run, stop, and remove, ensuring options like --detach, --publish, and environment variables are also considered. The run function will call the Docker client effectively, capturing any errors encountered during execution.

    Finally, I’ll put together the complete script along with usage instructions in a concise format. Below is a self‑contained Python CLI tool that uses the Docker SDK to manage containers (list, run, start, stop, remove, logs, exec).

    1. Prerequisites

    Install Docker SDK for Python:

    pip install docker
    

    Make sure Docker is running and your user can talk to the daemon (on Linux, being in the docker group or using sudo).


    2. The tool (docker_tool.py)

    Save this as docker_tool.py (or any name you like) and make it executable.

    #!/usr/bin/env python3
    """
    Simple Docker container manager using Docker SDK for Python.
    
    Commands:
      list          List containers
      run           Run a new container
      start         Start a stopped container
      stop          Stop a running container
      rm            Remove container(s)
      logs          Show logs from a container
      exec          Run a command inside a container
    """
    
    import argparse
    import sys
    
    import docker
    from docker.errors import NotFound, DockerException
    
    
    def get_client() -> docker.DockerClient:
        """Return a Docker client configured from environment."""
        return docker.from_env()
    
    
    # --------------------------
    # Helpers
    # --------------------------
    
    def parse_ports(port_strings):
        """
        Parse port mappings like ["8080:80", "5432:5432"] into a Docker ports dict.
    
        Returns: {"80/tcp": 8080, "5432/tcp": 5432}
        """
        if not port_strings:
            return {}
    
        ports = {}
        for mapping in port_strings:
            try:
                host_str, container_str = mapping.split(":")
                host_port = int(host_str)
                container_port = int(container_str)
            except ValueError:
                raise ValueError(
                    f"Invalid port mapping '{mapping}', "
                    "expected HOST:CONTAINER (e.g. 8080:80)"
                )
            ports[f"{container_port}/tcp"] = host_port
        return ports
    
    
    def parse_env(env_strings):
        """
        Parse env strings like ["KEY=value", "FOO=bar"] into a dict.
        """
        env = {}
        for item in env_strings or []:
            if "=" not in item:
                raise ValueError(
                    f"Invalid environment variable '{item}', "
                    "expected KEY=VALUE"
                )
            key, value = item.split("=", 1)
            env[key] = value
        return env
    
    
    # --------------------------
    # Command implementations
    # --------------------------
    
    def cmd_list(args):
        client = get_client()
        containers = client.containers.list(all=args.all)
    
        if not containers:
            print("No containers found.")
            return
    
        for c in containers:
            image = c.image.tags[0] if c.image.tags else c.image.id[:12]
            print(
                f"{c.short_id}\t"
                f"{c.name}\t"
                f"{c.status}\t"
                f"{image}"
            )
    
    
    def cmd_run(args):
        client = get_client()
    
        try:
            ports = parse_ports(args.ports)
            env = parse_env(args.env)
        except ValueError as e:
            print(e, file=sys.stderr)
            sys.exit(1)
    
        restart_policy = None
        if args.restart and args.restart != "no":
            restart_policy = {"Name": args.restart}
    
        command = args.command if args.command else None
    
        try:
            result = client.containers.run(
                args.image,
                command,
                name=args.name,
                detach=args.detach,
                ports=ports or None,
                environment=env or None,
                auto_remove=args.rm,
                restart_policy=restart_policy,
            )
        except DockerException as e:
            print(f"Docker error while running container: {e}", file=sys.stderr)
            sys.exit(1)
    
        # With detach=True, result is a Container; without detach it's the output.
        if args.detach:
            container = result
            print(f"Started container {container.short_id} (name={container.name})")
        else:
            output = result
            if isinstance(output, (bytes, bytearray)):
                sys.stdout.buffer.write(output)
            else:
                # Just in case; normally Docker SDK returns bytes here.
                print(output)
    
    
    def _get_container_or_exit(client, ident):
        try:
            return client.containers.get(ident)
        except NotFound:
            print(f"Container '{ident}' not found.", file=sys.stderr)
            sys.exit(1)
    
    
    def cmd_start(args):
        client = get_client()
        c = _get_container_or_exit(client, args.container)
        try:
            c.start()
        except DockerException as e:
            print(f"Failed to start container: {e}", file=sys.stderr)
            sys.exit(1)
        print(f"Started {c.short_id} (name={c.name})")
    
    
    def cmd_stop(args):
        client = get_client()
        c = _get_container_or_exit(client, args.container)
        try:
            c.stop(timeout=args.timeout)
        except DockerException as e:
            print(f"Failed to stop container: {e}", file=sys.stderr)
            sys.exit(1)
        print(f"Stopped {c.short_id} (name={c.name})")
    
    
    def cmd_rm(args):
        client = get_client()
    
        exit_code = 0
        for ident in args.container:
            try:
                c = client.containers.get(ident)
                c.remove(force=args.force)
                print(f"Removed {c.short_id} (name={c.name})")
            except NotFound:
                print(f"Container '{ident}' not found.", file=sys.stderr)
                exit_code = 1
            except DockerException as e:
                print(f"Failed to remove '{ident}': {e}", file=sys.stderr)
                exit_code = 1
    
        sys.exit(exit_code)
    
    
    def cmd_logs(args):
        client = get_client()
        c = _get_container_or_exit(client, args.container)
    
        try:
            if args.follow:
                for line in c.logs(stream=True, tail=args.tail):
                    sys.stdout.buffer.write(line)
            else:
                logs = c.logs(stream=False, tail=args.tail)
                sys.stdout.buffer.write(logs)
        except DockerException as e:
            print(f"Failed to fetch logs: {e}", file=sys.stderr)
            sys.exit(1)
    
    
    def cmd_exec(args):
        if not args.cmd:
            print("No command specified to exec.", file=sys.stderr)
            sys.exit(1)
    
        client = get_client()
        c = _get_container_or_exit(client, args.container)
    
        try:
            result = c.exec_run(args.cmd)
        except DockerException as e:
            print(f"Failed to exec in container: {e}", file=sys.stderr)
            sys.exit(1)
    
        if result.output:
            sys.stdout.buffer.write(result.output)
    
        # Propagate exit code from the command if available
        if result.exit_code is not None:
            sys.exit(result.exit_code)
    
    
    # --------------------------
    # Argument parser
    # --------------------------
    
    def build_parser():
        parser = argparse.ArgumentParser(
            description="Simple Docker container manager using Docker SDK"
        )
        subparsers = parser.add_subparsers(dest="command", metavar="<command>")
    
        # list
        p_list = subparsers.add_parser("list", help="List containers")
        p_list.add_argument(
            "-a", "--all",
            action="store_true",
            help="Show all containers (default: running only)",
        )
        p_list.set_defaults(func=cmd_list)
    
        # run
        p_run = subparsers.add_parser("run", help="Run a new container")
        p_run.add_argument("image", help="Image name (e.g. nginx:latest)")
        p_run.add_argument(
            "command",
            nargs=argparse.REMAINDER,
            help="Command to run in the container (optional)",
        )
        p_run.add_argument("-n", "--name", help="Assign a name to the container")
        p_run.add_argument(
            "-d", "--detach",
            action="store_true",
            help="Run container in background",
        )
        p_run.add_argument(
            "-p", "--publish",
            dest="ports",
            action="append",
            default=[],
            help="Publish a container's port to the host (HOST:CONTAINER). "
                 "Can be used multiple times.",
        )
        p_run.add_argument(
            "-e", "--env",
            action="append",
            default=[],
            help="Set environment variables (KEY=VALUE). Can be used multiple times.",
        )
        p_run.add_argument(
            "--restart",
            choices=["no", "always", "on-failure"],
            default="no",
            help="Restart policy (default: no)",
        )
        p_run.add_argument(
            "--rm",
            action="store_true",
            help="Automatically remove the container when it exits",
        )
        p_run.set_defaults(func=cmd_run)
    
        # start
        p_start = subparsers.add_parser("start", help="Start a stopped container")
        p_start.add_argument("container", help="Container name or ID")
        p_start.set_defaults(func=cmd_start)
    
        # stop
        p_stop = subparsers.add_parser("stop", help="Stop a running container")
        p_stop.add_argument("container", help="Container name or ID")
        p_stop.add_argument(
            "-t", "--timeout",
            type=int,
            default=10,
            help="Seconds to wait for stop before killing (default: 10)",
        )
        p_stop.set_defaults(func=cmd_stop)
    
        # rm
        p_rm = subparsers.add_parser("rm", help="Remove container(s)")
        p_rm.add_argument("container", nargs="+", help="Container name(s) or ID(s)")
        p_rm.add_argument(
            "-f", "--force",
            action="store_true",
            help="Force removal of running containers (equivalent to kill + rm)",
        )
        p_rm.set_defaults(func=cmd_rm)
    
        # logs
        p_logs = subparsers.add_parser("logs", help="Show container logs")
        p_logs.add_argument("container", help="Container name or ID")
        p_logs.add_argument(
            "-f", "--follow",
            action="store_true",
            help="Follow log output",
        )
        p_logs.add_argument(
            "--tail",
            default="all",
            help="Number of lines to show from the end of the logs (default: all)",
        )
        p_logs.set_defaults(func=cmd_logs)
    
        # exec
        p_exec = subparsers.add_parser("exec", help="Run a command in a container")
        p_exec.add_argument("container", help="Container name or ID")
        p_exec.add_argument(
            "cmd",
            nargs=argparse.REMAINDER,
            help="Command and args to run inside the container",
        )
        p_exec.set_defaults(func=cmd_exec)
    
        return parser
    
    
    def main():
        parser = build_parser()
        args = parser.parse_args()
    
        if not hasattr(args, "func"):
            parser.print_help()
            parser.exit(1)
    
        try:
            args.func(args)
        except DockerException as e:
            # Catch any Docker-related errors not already handled
            print(f"Docker error: {e}", file=sys.stderr)
            sys.exit(1)
    
    
    if __name__ == "__main__":
        main()
    

    3. Example usage

    # List running containers
    python docker_tool.py list
    
    # List all containers (including exited)
    python docker_tool.py list --all
    
    # Run nginx, publish port 8080 -> 80, in background
    python docker_tool.py run -d -p 8080:80 --name mynginx nginx:latest
    
    # Run a one-off container and print output
    python docker_tool.py run alpine:latest echo "hello from alpine"
    
    # Stop a container by name or ID
    python docker_tool.py stop mynginx
    
    # Start it again
    python docker_tool.py start mynginx
    
    # Show last 100 log lines
    python docker_tool.py logs mynginx --tail 100
    
    # Follow logs
    python docker_tool.py logs mynginx --follow
    
    # Exec a command inside a running container
    python docker_tool.py exec mynginx ls /usr/share/nginx/html
    
    # Remove a container
    python docker_tool.py rm mynginx
    

    If you want, I can help you extend this with image management (pull, list, prune), volumes, or networks.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.