python
#!/usr/bin/env python3
"""
Docker Manager CLI Tool
A simple Python CLI for managing Docker containers using docker-py and Click.
Requirements:
pip install click docker
Usage:
python docker_manager.py --help
python docker_manager.py ps
python docker_manager.py deploy nginx --name my-nginx --ports 8080:80
chmod +x docker_manager.py # to make executable
"""
import click
import docker
from docker.errors import NotFound, APIError
# Initialize Docker client
client = docker.from_env()
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
def cli():
"""Docker Manager CLI: Manage and deploy Docker containers."""
pass
@cli.command("ps")
@click.option("--all", "-a", is_flag=True, help="Show all containers (default: running only)")
@click.option("--format", "-f", type=str, default="{{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}",
help="Format output using Go template")
def ps(all):
"""List containers."""
try:
containers = client.containers.list(all=all)
for container in containers:
# Simple default format if no custom
click.echo(f"{container.short_id}\t{container.image}\t{container.status}\t{container.name}")
except Exception as e:
click.echo(f"Error listing containers: {e}", err=True)
@cli.command()
@click.argument("name")
def start(name):
"""Start a container."""
try:
container = client.containers.get(name)
container.start()
click.echo(f"Started container: {container.name}")
except NotFound:
click.echo(f"Container '{name}' not found.", err=True)
except Exception as e:
click.echo(f"Error starting container: {e}", err=True)
@cli.command()
@click.argument("name")
def stop(name):
"""Stop a container."""
try:
container = client.containers.get(name)
container.stop()
click.echo(f"Stopped container: {container.name}")
except NotFound:
click.echo(f"Container '{name}' not found.", err=True)
except Exception as e:
click.echo(f"Error stopping container: {e}", err=True)
@cli.command()
@click.argument("name")
@click.option("--force", "-f", is_flag=True, help="Force remove running container")
def rm(name, force):
"""Remove a container."""
try:
container = client.containers.get(name)
if not force and container.status == "running":
container.stop()
container.remove()
click.echo(f"Removed container: {name}")
except NotFound:
click.echo(f"Container '{name}' not found.", err=True)
except Exception as e:
click.echo(f"Error removing container: {e}", err=True)
@cli.command()
@click.argument("image")
@click.option("--name", "-n", help="Container name")
@click.option("--detach", "-d", is_flag=True, default=True, help="Run in detached mode")
@click.option("--ports", "-p", "ports", multiple=True, help="Port mapping: HOST:CONTAINER (e.g., 8080:80)")
@click.option("--volume", "-v", "volumes", multiple=True, help="Volume mapping: HOST:CONTAINER (e.g., /host:/container)")
@click.option("--env", "-e", "env_vars", multiple=True, help="Environment variable: KEY=VALUE")
@click.option("--rm", is_flag=True, help="Auto-remove container on exit")
def deploy(image, name, detach, ports, volumes, env_vars, rm):
"""Deploy (run) a new container from an image."""
try:
kwargs = {
"detach": detach,
"remove": rm,
}
if name:
kwargs["name"] = name
# Port bindings
port_bindings = {}
for port in ports:
if ":" not in port:
raise click.BadParameter("Ports must be in HOST:CONTAINER format")
host_port, container_port = port.split(":", 1)
port_bindings[container_port] = int(host_port)
if port_bindings:
kwargs["ports"] = port_bindings
# Volume bindings
binds = []
for volume in volumes:
if ":" not in volume:
raise click.BadParameter("Volumes must be in HOST:CONTAINER format")
host_path, container_path = volume.split(":", 1)
binds.append(f"{host_path}:{container_path}")
if binds:
kwargs["volumes"] = binds # docker-py handles string binds
# Environment
if env_vars:
kwargs["environment"] = env_vars
container = client.containers.run(image, **kwargs)
click.echo(f"Deployed container: {container.name} (ID: {container.short_id})")
except click.BadParameter as e:
click.echo(f"Invalid argument: {e}", err=True)
except APIError as e:
click.echo(f"Docker API error: {e}", err=True)
except Exception as e:
click.echo(f"Error deploying container: {e}", err=True)
@cli.command()
@click.argument("name")
@click.option("--follow", "-f", is_flag=True, help="Follow log output")
@click.option("--tail", type=int, default=None, help="Number of lines to show from end")
def logs(name, follow, tail):
"""Show container logs."""
try:
container = client.containers.get(name)
stream = follow
logs = container.logs(stream=stream, follow=follow, tail=tail)
if stream:
for log in logs:
click.echo(log.decode().rstrip())
else:
click.echo(logs.decode())
except NotFound:
click.echo(f"Container '{name}' not found.", err=True)
except Exception as e:
click.echo(f"Error fetching logs: {e}", err=True)
@cli.command()
@click.argument("name")
@click.argument("cmd", nargs=-1, required=True)
def exec_cmd(name, cmd):
"""Execute a command in a running container."""
try:
container = client.containers.get(name)
command = " ".join(cmd)
exit_code, output = container.exec_run(command)
click.echo(output.decode())
if exit_code != 0:
click.echo(f"Command exited with code {exit_code}", err=True)
except NotFound:
click.echo(f"Container '{name}' not found.", err=True)
except Exception as e:
click.echo(f"Error executing command: {e}", err=True)
@cli.command()
def images():
"""List Docker images."""
try:
images_list = client.images.list(all=True)
for img in images_list:
tags = ", ".join(img.tags) if img.tags else "<none>"
click.echo(f"{img.short_id}\t{tags}\t{'<none>' if not img.labels else list(img.labels.keys())}")
except Exception as e:
click.echo(f"Error listing images: {e}", err=True)
if __name__ == "__main__":
cli()
This tool provides a solid foundation for Docker container management via CLI. Extend it as needed!