The user wants a Python tool to manage Docker containers using the Docker SDK.
This tool needs to be functional, readable, and ideally cover common use cases:
Listing containers (running and stopped).
Creating/Running a container.
Starting a stopped container.
Stopping a running container.
Removing a container.
maybe inspecting logs.
I should use the official docker Python library (pip install docker).
Structure of the tool:
A CLI (Command Line Interface) is the most logical format for a "management tool". I'll use argparse or click for parsing arguments. argparse is built-in, so it keeps dependencies low, but click is nicer. Let's stick to argparse for a standard Python script without extra external dependencies besides docker. Or, better yet, I can create a class-based structure that wraps the Docker SDK and then a simple CLI entry point.
Core Class: DockerManager
__init__: Connect to the Docker daemon.
list_containers(all=False): Returns a list of containers.
run_container(image, command, name, ports, detach=True): Runs a new container.
stop_container(container_id): Stops a container.
start_container(container_id): Starts a container.
remove_container(container_id, force=False): Removes a container.
get_logs(container_id): Fetches logs.
Error Handling:
Docker operations can fail (container not found, image not found, API connection error). I need to wrap calls in try-except blocks and handle docker.errors.
Implementation Details:
Import:import docker
Client:client = docker.from_env()
Refining the CLI approach:
I will provide a script that can be run from the terminal.
Example commands:
python docker_tool.py listpython docker_tool.py run --image nginx --name my-webpython docker_tool.py stop <id>python docker_tool.py logs <id>
Method run: client.containers.run(...). Needs detach=True usually for a management tool so it doesn't hang the script.
Method stop: Get container object, call .stop().
Method start: Get container object, call .start().
Method rm: Get container object, call .remove().
Method logs: Get container object, call .logs().
Argparse Setup: Define subparsers for the actions (list, run, stop, etc.).
Main Block: Parse args and call the appropriate class method.
Self-Correction/Edge Cases:
Permissions: Docker often requires sudo. The user needs to be warned or ensure their user is in the docker group.
Container ID vs Name: The SDK accepts both, which is great. I'll label the argument as identifier to be clear.
Formatting: Output should be clean. Using f-strings is good.
Let's write the code. I'll create a comprehensive single-file script.
Prerequisites: Mention pip install docker.
Code Structure:
Imports.
DockerManager class.
main function for CLI logic.
if __name__ == "__main__": block.
Specific Logic for run:
Running a container is complex (ports, volumes, env vars). For a basic tool, I should support the basics (image, name, ports, detach) but keep the CLI simple. I'll add --ports support.
Specific Logic for logs:
Logs return bytes in Python 3. Need to decode them (.decode('utf-8')).
Result:
A complete Python script that acts as a CLI wrapper around the Docker SDK.
Let's structure the response:
Prerequisites (Install SDK).
The complete Python script.
Explanation of how to use it (Examples).
Brief explanation of the code logic.
This covers the user request perfectly. It's a tool, it uses the SDK, and it's in Python.
(Self-Correction during drafting code): When using argparse with subparsers, ensure the handling of arguments is correct. For example, run needs --image. stop needs container_id.
I will add comments explaining the specific Docker SDK calls being made (e.g., docker.from_env(), client.containers.list()).
One nice addition: formatting the list output using columns so it looks like docker ps. I can just use tabs or f-strings with padding.
Final check of requirements:
Manage containers? Yes.
Docker SDK? Yes.
Python? Yes.
The solution is solid. I will present the code clearly.
Here is a complete, functional Python tool to manage Docker containers using the official docker SDK.
Prerequisites
First, you need to install the Docker SDK for Python:
bash
pip install docker
You also need the Docker daemon running on your machine (e.g., Docker Desktop).
The Python Script (docker_tool.py)
This script uses argparse to create a command-line interface. It wraps the Docker SDK to perform lifecycle operations like listing, running, stopping, and removing containers.
python
How to use this tool
Save the code above into a file named docker_tool.py. You can then run it from your terminal.
1. List running containers:
bash
python docker_tool.py list
2. List all containers (including stopped ones):
bash
python docker_tool.py list -a
3. Run a new container (e.g., Nginx):
bash
python docker_tool.py run nginx --name my-web-server -p 8080:80
This maps port 8080 on your machine to port 80 inside the container.
4. View logs:
bash
python docker_tool.py logs my-web-server
5. Stop a container:
bash
python docker_tool.py stop my-web-server
6. Start a stopped container:
bash
python docker_tool.py start my-web-server
7. Remove a container:
bash
python docker_tool.py rm my-web-server
(Add -f flag to force remove a running container)
Key Concepts Used
docker.from_env(): This initializes the client by reading environment variables or the default Docker context configuration (same as if you were running docker CLI commands).
client.containers.list(): Replaces the CLI command docker ps.
client.containers.run(): This is a high-level helper that creates AND starts a container. It is equivalent to docker run.
client.containers.get(): Used to retrieve a specific container object by name or ID so you can perform actions on it (like .stop() or .remove()).
argparse: Used to create the user-friendly command-line structure with subcommands (list, run, stop, etc.).
import docker
import argparse
import sys
# Initialize the Docker client
try:
client = docker.from_env()
except docker.errors.DockerException as e:
print(f"Error connecting to Docker daemon: {e}")
sys.exit(1)
class DockerManager:
def __init__(self, client):
self.client = client
def list_containers(self, all=False):
"""List all containers."""
try:
containers = self.client.containers.list(all=all)
if not containers:
print("No containers found.")
return
print(f"{'ID':<12} {'NAME':<20} {'STATUS':<15} {'IMAGE':<20}")
print("-" * 70)
for c in containers:
# c.id is long, usually we want the short 12-char ID
short_id = c.short_id
name = c.name
status = c.status
image = c.image.tags[0] if c.image.tags else c.image.short_id
print(f"{short_id:<12} {name:<20} {status:<15} {image:<20}")
except Exception as e:
print(f"Error listing containers: {e}")
def run_container(self, image, name=None, command=None, detach=True, ports=None):
"""Run a new container."""
print(f"Running container from image '{image}'...")
try:
# Handling port mapping if provided (e.g., "8080:80")
port_bindings = {}
if ports:
# Expects format "HOST:CONTAINER"
parts = ports.split(':')
if len(parts) == 2:
port_bindings = {f"{parts[1]}/tcp": int(parts[0])}
container = self.client.containers.run(
image,
command=command,
name=name,
detach=detach,
ports=port_bindings
)
print(f"Container started: {container.name} (ID: {container.short_id})")
except docker.errors.ImageNotFound:
print(f"Error: Image '{image}' not found. Try pulling it first.")
except docker.errors.APIError as e:
print(f"Error running container: {e}")
def stop_container(self, identifier):
"""Stop a running container."""
try:
container = self.client.containers.get(identifier)
print(f"Stopping container {container.name}...")
container.stop()
print("Container stopped.")
except docker.errors.NotFound:
print(f"Error: Container '{identifier}' not found.")
except Exception as e:
print(f"Error stopping container: {e}")
def start_container(self, identifier):
"""Start a stopped container."""
try:
container = self.client.containers.get(identifier)
print(f"Starting container {container.name}...")
container.start()
print("Container started.")
except docker.errors.NotFound:
print(f"Error: Container '{identifier}' not found.")
except Exception as e:
print(f"Error starting container: {e}")
def remove_container(self, identifier, force=False):
"""Remove a container."""
try:
container = self.client.containers.get(identifier)
print(f"Removing container {container.name}...")
container.remove(force=force)
print("Container removed.")
except docker.errors.NotFound:
print(f"Error: Container '{identifier}' not found.")
except docker.errors.APIError as e:
if "running" in str(e).lower():
print("Error: Container is running. Use --force to remove a running container.")
else:
print(f"Error removing container: {e}")
def get_logs(self, identifier):
"""Fetch logs from a container."""
try:
container = self.client.containers.get(identifier)
print(f"--- Logs for {container.name} ---")
# stream=False returns a string/bytes block
logs = container.logs(tail=100).decode('utf-8')
print(logs)
except docker.errors.NotFound:
print(f"Error: Container '{identifier}' not found.")
def main():
manager = DockerManager(client)
parser = argparse.ArgumentParser(description="Simple 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 just running)")
# Run command
parser_run = subparsers.add_parser("run", help="Run a container")
parser_run.add_argument("image", help="Image name (e.g., nginx, python:3.9)")
parser_run.add_argument("--name", help="Container name")
parser_run.add_argument("-p", "--ports", help="Port mapping (e.g., 8080:80)")
parser_run.add_argument("-d", "--detach", action="store_true", default=True, help="Run in detached mode")
# Stop command
parser_stop = subparsers.add_parser("stop", help="Stop a container")
parser_stop.add_argument("identifier", help="Container ID or Name")
# Start command
parser_start = subparsers.add_parser("start", help="Start a container")
parser_start.add_argument("identifier", help="Container ID or Name")
# Remove command
parser_rm = subparsers.add_parser("rm", help="Remove a container")
parser_rm.add_argument("identifier", help="Container ID or Name")
parser_rm.add_argument("-f", "--force", action="store_true", help="Force remove running container")
# Logs command
parser_logs = subparsers.add_parser("logs", help="View container logs")
parser_logs.add_argument("identifier", help="Container ID or Name")
args = parser.parse_args()
if args.command == "list":
manager.list_containers(all=args.all)
elif args.command == "run":
manager.run_container(args.image, name=args.name, ports=args.ports, detach=args.detach)
elif args.command == "stop":
manager.stop_container(args.identifier)
elif args.command == "start":
manager.start_container(args.identifier)
elif args.command == "rm":
manager.remove_container(args.identifier, force=args.force)
elif args.command == "logs":
manager.get_logs(args.identifier)
else:
parser.print_help()
if __name__ == "__main__":
main()