Envisioning the CLI
I'm now zeroing in on the core functionality: a Python CLI tool. The immediate focus is on managing and deploying Docker containers. Key aspects include user-friendliness and efficiency. This will be an essential foundation for the more complex features planned later.
Pinpointing Essential Features
My focus is narrowing in on the specific requirements for container management via CLI. The language will definitely be Python, and the central tasks will be starting, stopping, listing, and removing Docker containers, alongside deployment operations like pulling and running images. I'm leaning toward using either click or typer to streamline the CLI design, but click seems like the industry-standard choice. The docker SDK is the clear winner for Docker interactions.
Structuring the Commands
I'm now concretizing the command structure. It's becoming clearer what features are essential: listing running or all containers, deploying images, stopping, starting, and removing containers, and maybe a logs view. I'm focusing on the click command structure to manage these operations effectively. I'll need flags and output formatting to make the CLI usable and readable.
Formalizing Command Definitions
I'm presently building out the CLI commands. I've designed the list command to optionally show all containers. The deploy command now has argument parsing for image, and options for name and port. Stop has a container ID argument. I'm focused on clean argument handling and concise functionality.
Addressing Error Conditions
I'm now integrating error handling and formatting. I'm focusing on user-friendly outputs. Wrapping Docker calls in try-except blocks, specifically for API and not found errors, is the main priority. I'm also planning to use click.echo with colors for more visually appealing and informative feedback. Additionally, I'm working on the correct port mapping format for Docker.
Clarifying Port Handling
I'm presently refining the port logic. I'm focusing on parsing and validating the port mapping format for the run command. Specifically, I'm ensuring the proper conversion of the --ports argument to the docker SDK's required format. The handling of the colon-separated input and the inversion of the host:container port assignment is the crux of this.
Finalizing Documentation
Now I'm creating the user guide. I will explain the prerequisites, installation with pip, and provide clear usage examples. I'll also explain the code and its major sections. I'll ensure the instructions are easy to follow and comprehensive.
This is a complete project for a Python CLI tool named DockMan (Docker Manager). It uses the Click library for the command-line interface and the official Docker SDK for Python to interact with the Docker engine.
Prerequisites
You will need:
- Python 3.x installed.
- Docker installed and running on your machine.
1. Project Setup
Create a folder for your project and create these two files:
File: requirements.txt
click
docker
tabulate
File: dockman.py
2. The Python Code
Here is the complete source code. I have included error handling, colorized output, and a cleanly formatted list view.
import click
import docker
from docker.errors import APIError, NotFound
from tabulate import tabulate
# Initialize Docker Client
try:
client = docker.from_env()
except docker.errors.DockerException:
click.secho("Error: Docker is not running. Please start Docker and try again.", fg="red", bold=True)
exit(1)
@click.group()
def cli():
"""DockMan: A CLI tool to manage Docker containers."""
pass
# --- COMMAND: LIST ---
@cli.command()
@click.option('--all', '-a', is_flag=True, help="Show all containers (default shows just running)")
def ls(all):
"""List containers."""
try:
containers = client.containers.list(all=all)
if not containers:
click.echo("No containers found.")
return
data = []
for c in containers:
status_color = "green" if c.status == "running" else "red"
short_id = c.short_id
image = c.image.tags[0] if c.image.tags else c.image.id[:12]
name = c.name
status = click.style(c.status.upper(), fg=status_color)
ports = str(c.ports) if c.ports else ""
data.append([short_id, name, image, status, ports])
headers = ["ID", "Name", "Image", "Status", "Ports"]
click.echo(tabulate(data, headers=headers, tablefmt="simple"))
except APIError as e:
click.secho(f"Error listing containers: {e}", fg="red")
# --- COMMAND: DEPLOY (RUN) ---
@cli.command()
@click.argument('image')
@click.option('--name', '-n', help="Name for the container")
@click.option('--ports', '-p', help="Port mapping (format: host_port:container_port, e.g., 8080:80)")
@click.option('--bg', '-d', is_flag=True, default=True, help="Run in detached mode (background)")
def deploy(image, name, ports, bg):
"""Pull an image and run a container."""
try:
# Handle port mapping parsing
port_bindings = {}
if ports:
try:
host_port, container_port = ports.split(':')
# Docker SDK expects {'container_port/tcp': host_port}
port_bindings = {f'{container_port}/tcp': host_port}
except ValueError:
click.secho("Invalid port format. Use host:container (e.g., 8080:80)", fg="red")
return
click.secho(f"Pulling image {image}...", fg="blue")
try:
client.images.pull(image)
click.secho("Image pulled successfully.", fg="green")
except APIError:
click.secho(f"Could not pull image {image}. Trying local cache...", fg="yellow")
click.echo(f"Starting container...")
container = client.containers.run(
image,
name=name,
ports=port_bindings,
detach=bg
)
click.secho(f"Container started successfully: {container.name} ({container.short_id})", fg="green", bold=True)
except APIError as e:
click.secho(f"Docker API Error: {e}", fg="red")
except Exception as e:
click.secho(f"Error: {e}", fg="red")
# --- COMMAND: STOP ---
@cli.command()
@click.argument('container_id')
def stop(container_id):
"""Stop a running container by ID or Name."""
try:
container = client.containers.get(container_id)
click.echo(f"Stopping {container.name}...")
container.stop()
click.secho(f"Container {container.name} stopped.", fg="yellow")
except NotFound:
click.secho(f"Container '{container_id}' not found.", fg="red")
except APIError as e:
click.secho(f"Error stopping container: {e}", fg="red")
# --- COMMAND: START ---
@cli.command()
@click.argument('container_id')
def start(container_id):
"""Start a stopped container by ID or Name."""
try:
container = client.containers.get(container_id)
click.echo(f"Starting {container.name}...")
container.start()
click.secho(f"Container {container.name} is now running.", fg="green")
except NotFound:
click.secho(f"Container '{container_id}' not found.", fg="red")
except APIError as e:
click.secho(f"Error starting container: {e}", fg="red")
# --- COMMAND: REMOVE ---
@cli.command()
@click.argument('container_id')
@click.option('--force', '-f', is_flag=True, help="Force removal (kills running container)")
def rm(container_id, force):
"""Remove a container."""
try:
container = client.containers.get(container_id)
container.remove(force=force)
click.secho(f"Container {container.name} removed.", fg="red")
except NotFound:
click.secho(f"Container '{container_id}' not found.", fg="red")
except APIError as e:
click.secho(f"Error removing container: {e}", fg="red")
# --- COMMAND: LOGS ---
@cli.command()
@click.argument('container_id')
@click.option('--tail', default=10, help="Number of lines to show")
def logs(container_id, tail):
"""Fetch logs from a container."""
try:
container = client.containers.get(container_id)
logs = container.logs(tail=tail).decode("utf-8")
click.echo(logs)
except NotFound:
click.secho(f"Container '{container_id}' not found.", fg="red")
if __name__ == '__main__':
cli()
3. Installation and Usage Guide
Step 1: Install Dependencies
Open your terminal in the project folder and run:
pip install -r requirements.txt
Step 2: How to use the tool
1. Deploy a new container (e.g., Nginx)
This will pull the latest nginx image and map localhost port 8080 to the container's port 80.
python dockman.py deploy nginx --name my-web-server --ports 8080:80
2. List Containers
View running containers:
python dockman.py ls
View all containers (including stopped ones):
python dockman.py ls --all
3. View Logs
See the last 10 lines of logs:
python dockman.py logs my-web-server
4. Stop a Container
python dockman.py stop my-web-server
5. Remove a Container
python dockman.py rm my-web-server
Key Features Explained
docker.from_env(): This initializes the connection to your local Docker daemon using environment variables or the default socket.
- Click Groups (
@click.group): This allows us to nest commands (like git commit, git push). Here we use python dockman.py [command].
- Tabulate: The
ls command uses tabulate to pretty-print the list of containers into a readable ASCII table.
- Arguments & Options:
@click.argument: Required inputs (like the image name).
@click.option: Optional flags (like --name or --ports).
- Error Handling: The
try...except blocks catch specific Docker errors (NotFound, APIError) so the program doesn't crash with an ugly stack trace if you mistype an ID.
Optional: Turn it into a system command
If you want to run dockman instead of python dockman.py, you can add this to your setup.py or create a simple alias in your shell:
alias dockman="python /path/to/your/dockman.py"