Skip to content
TheChatArchiveThe Chat Archive
GeminiGemini 3 Pro Preview· googleHugging 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. Gemini Assistant

    Outlining the Strategy

    I'm currently focused on the core requirements of this Python tool. Considering the user's need, I'm defining the functionalities: container creation, starting, stopping, removal, and log viewing. I am also investigating the best way to handle user input for ease of use.

    Defining Core Functions

    I've moved from the planning stage to implementation. I am constructing the DockerManager class, and defining methods to list containers, create new containers from an image (specifying ports and volumes), start, stop, and remove them. Error handling is critical; I'm implementing try-except blocks with docker.errors to deal with potential issues.

    Enhancing the Error Handling

    I'm now diving deeper into exception handling. Specifically, I'm working on wrapping each Docker operation (create, start, stop, remove, logs) within try-except blocks. I'm focusing on catching docker.errors.NotFound, docker.errors.APIError, and general Exception to provide informative error messages to the user. I'm also considering logging errors for debugging.

    Finalizing the Implementation

    I'm wrapping up the code, adding the argparse integration. I'm focusing on parsing the ports argument to correctly map host ports to container ports. Also, I'm incorporating the suggested docstrings and basic formatting to the tool. It's time to test this tool locally, before considering any external dependencies.

    Finalizing Tool Design

    I'm now fully immersed in the design phase, and am finalizing the structure of the Python tool. I'm focusing on defining the command-line interface with argparse, considering arguments for run, stop, list, and rm. The run command's port mapping needs careful parsing. I'm also planning for clear usage examples.

    This requires the Docker SDK for Python. This tool allows you to perform common Docker operations (List, Run, Stop, Start, Remove, Logs) directly from the command line using Python.

    Prerequisites

    You need to install the docker python library:

    pip install docker
    

    Note: Ensure Docker Desktop (Windows/Mac) or the Docker Engine (Linux) is running before using this tool.

    The Python Docker Tool (dockermanager.py)

    Save the following code into a file named dockermanager.py.

    import docker
    import argparse
    import sys
    
    class DockerManager:
        def __init__(self):
            try:
                # Connect to Docker using default environment settings
                self.client = docker.from_env()
            except docker.errors.DockerException as e:
                print(f"Error: Could not connect to Docker. Is it running? \nDetails: {e}")
                sys.exit(1)
    
        def list_containers(self, show_all=False):
            """Lists containers."""
            try:
                containers = self.client.containers.list(all=show_all)
                if not containers:
                    print("No containers found.")
                    return
    
                print(f"{'ID':<15} {'NAME':<25} {'STATUS':<15} {'IMAGE':<20}")
                print("-" * 75)
                for container in containers:
                    # Shorten ID for readability
                    short_id = container.short_id
                    name = container.name[:24]
                    status = container.status
                    image = container.image.tags[0] if container.image.tags else "n/a"
                    print(f"{short_id:<15} {name:<25} {status:<15} {image:<20}")
            except Exception as e:
                print(f"Error listing containers: {e}")
    
        def run_container(self, image, name=None, ports=None, detach=True):
            """Runs a new container."""
            try:
                print(f"Pulling image {image} (if not present)...")
                
                # Convert ports string "8080:80" to dict {80: 8080} for the SDK
                port_bindings = {}
                if ports:
                    for p in ports:
                        host_p, container_p = p.split(':')
                        port_bindings[container_p] = host_p
    
                container = self.client.containers.run(
                    image,
                    name=name,
                    ports=port_bindings,
                    detach=detach
                )
                print(f"Container started successfully. ID: {container.short_id}, Name: {container.name}")
            except docker.errors.ImageNotFound:
                print(f"Error: Image '{image}' not found.")
            except docker.errors.APIError as e:
                print(f"Docker API Error: {e}")
            except Exception as e:
                print(f"Error: {e}")
    
        def stop_container(self, container_identifier):
            """Stops a running container by ID or Name."""
            try:
                container = self.client.containers.get(container_identifier)
                print(f"Stopping container {container.name}...")
                container.stop()
                print("Container stopped.")
            except docker.errors.NotFound:
                print(f"Error: Container '{container_identifier}' not found.")
            except Exception as e:
                print(f"Error: {e}")
    
        def start_container(self, container_identifier):
            """Starts a stopped container."""
            try:
                container = self.client.containers.get(container_identifier)
                print(f"Starting container {container.name}...")
                container.start()
                print("Container started.")
            except docker.errors.NotFound:
                print(f"Error: Container '{container_identifier}' not found.")
            except Exception as e:
                print(f"Error: {e}")
    
        def remove_container(self, container_identifier, force=False):
            """Removes a container."""
            try:
                container = self.client.containers.get(container_identifier)
                print(f"Removing container {container.name}...")
                container.remove(force=force)
                print("Container removed.")
            except docker.errors.NotFound:
                print(f"Error: Container '{container_identifier}' not found.")
            except Exception as e:
                print(f"Error: {e}")
    
        def get_logs(self, container_identifier, tail=10):
            """Gets logs from a container."""
            try:
                container = self.client.containers.get(container_identifier)
                logs = container.logs(tail=tail).decode("utf-8")
                print(f"--- Logs for {container.name} ---")
                print(logs)
            except docker.errors.NotFound:
                print(f"Error: Container '{container_identifier}' not found.")
            except Exception as e:
                print(f"Error: {e}")
    
    # CLI Setup
    def main():
        manager = DockerManager()
        
        parser = argparse.ArgumentParser(description="Python Docker Management Tool")
        subparsers = parser.add_subparsers(dest="command", help="Available commands")
    
        # List command
        parser_list = subparsers.add_parser("list", help="List containers")
        parser_list.add_argument("-a", "--all", action="store_true", help="Show all containers (default shows running)")
    
        # Run command
        parser_run = subparsers.add_parser("run", help="Run a container")
        parser_run.add_argument("image", help="Image name (e.g., nginx)")
        parser_run.add_argument("--name", help="Container name")
        parser_run.add_argument("-p", "--port", action="append", help="Port mapping host:container (e.g., 8080:80)")
    
        # Stop command
        parser_stop = subparsers.add_parser("stop", help="Stop a container")
        parser_stop.add_argument("id", help="Container ID or Name")
    
        # Start command
        parser_start = subparsers.add_parser("start", help="Start a container")
        parser_start.add_argument("id", help="Container ID or Name")
    
        # Remove command
        parser_rm = subparsers.add_parser("rm", help="Remove a container")
        parser_rm.add_argument("id", help="Container ID or Name")
        parser_rm.add_argument("-f", "--force", action="store_true", help="Force remove (if running)")
    
        # Logs command
        parser_logs = subparsers.add_parser("logs", help="View container logs")
        parser_logs.add_argument("id", help="Container ID or Name")
        parser_logs.add_argument("--tail", type=int, default=20, help="Number of lines to show")
    
        args = parser.parse_args()
    
        if args.command == "list":
            manager.list_containers(show_all=args.all)
        elif args.command == "run":
            manager.run_container(args.image, name=args.name, ports=args.port)
        elif args.command == "stop":
            manager.stop_container(args.id)
        elif args.command == "start":
            manager.start_container(args.id)
        elif args.command == "rm":
            manager.remove_container(args.id, force=args.force)
        elif args.command == "logs":
            manager.get_logs(args.id, tail=args.tail)
        else:
            parser.print_help()
    
    if __name__ == "__main__":
        main()
    

    How to use the tool

    Open your terminal and run the following commands:

    1. Run a container

    Run an Nginx server mapping port 8080 on your machine to port 80 in the container.

    python dockermanager.py run nginx --name my-web-server -p 8080:80
    

    2. List running containers

    python dockermanager.py list
    

    To see stopped containers as well:

    python dockermanager.py list --all
    

    3. Check Logs

    Get the last 20 lines of logs from the container.

    python dockermanager.py logs my-web-server
    

    4. Stop a container

    You can use the name or the Container ID.

    python dockermanager.py stop my-web-server
    

    5. Start a container

    python dockermanager.py start my-web-server
    

    6. Remove a container

    # Stop it first, or use --force
    python dockermanager.py rm my-web-server --force
    

    How it works

    1. docker.from_env(): This looks for standard Docker environment variables or the Docker socket (/var/run/docker.sock on Linux/Mac, or the named pipe on Windows) to connect your script to the Docker daemon.
    2. client.containers: This object behaves like a list manager. We use .list(), .get(id), and .run() to manipulate containers.
    3. Argparse: The script uses Python's standard argparse library to create a CLI structure (subcommands like run, stop, list), making it act like a real system tool.

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