#!/usr/bin/env python3
"""
dockermgr: Simple CLI to manage and deploy Docker containers.
Features:
- List containers and images
- Build Docker images
- Run containers with ports/env
- Stop and remove containers
- View container logs
- "Deploy" an image (pull + replace existing container)
Requires:
pip install docker
And a running Docker daemon.
"""
import argparse
import sys
from typing import Dict, List, Optional
import docker
from docker.errors import APIError, NotFound, DockerException
# --------------- Helpers ---------------
def get_client() -> docker.DockerClient:
try:
return docker.from_env()
except DockerException as e:
print(f"Error: could not connect to Docker daemon: {e}", file=sys.stderr)
sys.exit(1)
def parse_ports(port_list: Optional[List[str]]) -> Dict[str, int]:
"""
Parse -p/--port HOST:CONTAINER into Docker SDK format.
Only supports simple HOSTPORT:CONTAINERPORT (TCP).
"""
ports: Dict[str, int] = {}
if not port_list:
return ports
for mapping in port_list:
try:
host, container = mapping.split(":", 1)
host = host.strip()
container = container.strip()
if not host.isdigit() or not container.isdigit():
raise ValueError
container_key = f"{container}/tcp" # assume TCP
ports[container_key] = int(host)
except ValueError:
print(
f"Invalid port mapping '{mapping}'. "
f"Expected format HOSTPORT:CONTAINERPORT, e.g. 8080:80",
file=sys.stderr,
)
sys.exit(1)
return ports
def parse_env(env_list: Optional[List[str]]) -> Dict[str, str]:
"""
Parse -e/--env KEY=VALUE into dict.
"""
env: Dict[str, str] = {}
if not env_list:
return env
for item in env_list:
if "=" not in item:
print(
f"Invalid environment variable '{item}'. "
f"Expected format KEY=VALUE",
file=sys.stderr,
)
sys.exit(1)
key, value = item.split("=", 1)
env[key] = value
return env
def handle_api_error(e: APIError) -> int:
print(f"Docker API error: {e.explanation or e}", file=sys.stderr)
return 1
# --------------- Command implementations ---------------
def cmd_list(args: argparse.Namespace) -> int:
client = get_client()
try:
containers = client.containers.list(all=args.all)
except APIError as e:
return handle_api_error(e)
if not containers:
print("No containers found.")
return 0
print(f"{'ID':<12} {'NAME':<25} {'STATUS':<20} IMAGE")
for c in containers:
image = c.image.tags[0] if c.image.tags else c.image.short_id
print(f"{c.short_id:<12} {c.name:<25} {c.status:<20} {image}")
return 0
def cmd_images(args: argparse.Namespace) -> int:
client = get_client()
try:
images = client.images.list()
except APIError as e:
return handle_api_error(e)
if not images:
print("No images found.")
return 0
print(f"{'ID':<20} TAGS")
for img in images:
tags = ", ".join(img.tags) if img.tags else "<none>"
print(f"{img.short_id:<20} {tags}")
return 0
def cmd_build(args: argparse.Namespace) -> int:
client = get_client()
try:
print(f"Building image from {args.path} with tag '{args.tag}'...")
image, logs = client.images.build(
path=args.path,
tag=args.tag,
dockerfile=args.dockerfile,
rm=True,
pull=args.pull,
)
for line in logs:
text = line.get("stream") or line.get("status") or ""
if text:
sys.stdout.write(text)
print(f"\nBuilt image: {image.short_id} ({', '.join(image.tags) or 'untagged'})")
return 0
except APIError as e:
return handle_api_error(e)
def cmd_run(args: argparse.Namespace) -> int:
client = get_client()
ports = parse_ports(args.port)
env = parse_env(args.env)
run_kwargs = {
"image": args.image,
"name": args.name,
"detach": args.detach,
"ports": ports or None,
"environment": env or None,
"restart_policy": {"Name": args.restart} if args.restart else None,
}
# Remove keys with value None to avoid confusing the SDK
run_kwargs = {k: v for k, v in run_kwargs.items() if v is not None}
try:
container = client.containers.run(**run_kwargs)
print(f"Started container {container.name} ({container.short_id})")
if not args.detach:
# Attach and stream logs until container exits
for line in container.logs(stream=True, follow=True):
sys.stdout.write(line.decode(errors="replace"))
return 0
except APIError as e:
return handle_api_error(e)
def cmd_stop(args: argparse.Namespace) -> int:
client = get_client()
failed = False
for ident in args.containers:
try:
container = client.containers.get(ident)
print(f"Stopping {container.name} ({container.short_id})...")
container.stop(timeout=args.timeout)
except NotFound:
print(f"Container not found: {ident}", file=sys.stderr)
failed = True
except APIError as e:
handle_api_error(e)
failed = True
return 1 if failed else 0
def cmd_rm(args: argparse.Namespace) -> int:
client = get_client()
failed = False
for ident in args.containers:
try:
container = client.containers.get(ident)
print(f"Removing {container.name} ({container.short_id})...")
container.remove(force=args.force)
except NotFound:
print(f"Container not found: {ident}", file=sys.stderr)
failed = True
except APIError as e:
handle_api_error(e)
failed = True
return 1 if failed else 0
def cmd_logs(args: argparse.Namespace) -> int:
client = get_client()
try:
container = client.containers.get(args.container)
except NotFound:
print(f"Container not found: {args.container}", file=sys.stderr)
return 1
except APIError as e:
return handle_api_error(e)
try:
if args.follow:
for line in container.logs(stream=True, follow=True, tail=args.tail):
sys.stdout.write(line.decode(errors="replace"))
else:
output = container.logs(tail=args.tail)
sys.stdout.write(output.decode(errors="replace"))
return 0
except APIError as e:
return handle_api_error(e)
except KeyboardInterrupt:
return 0
def cmd_deploy(args: argparse.Namespace) -> int:
"""
Simple "deploy" strategy:
- If a container with --name exists:
stop it and remove it
- Pull the image (unless --no-pull)
- Run a new container with the same name/ports/env/restart
"""
client = get_client()
ports = parse_ports(args.port)
env = parse_env(args.env)
# Stop/remove existing container with this name, if any
try:
existing = client.containers.get(args.name)
print(f"Found existing container {existing.name} ({existing.short_id}), replacing...")
existing.stop(timeout=args.timeout)
existing.remove()
except NotFound:
pass # nothing to replace
except APIError as e:
return handle_api_error(e)
# Pull latest image
if not args.no_pull:
try:
print(f"Pulling image {args.image}...")
for line in client.api.pull(args.image, stream=True, decode=True):
status = line.get("status")
progress = line.get("progress", "")
if status:
print(f"{status} {progress}")
except APIError as e:
return handle_api_error(e)
run_kwargs = {
"image": args.image,
"name": args.name,
"detach": True,
"ports": ports or None,
"environment": env or None,
"restart_policy": {"Name": args.restart} if args.restart else None,
}
run_kwargs = {k: v for k, v in run_kwargs.items() if v is not None}
try:
container = client.containers.run(**run_kwargs)
print(f"Deployed {container.name} ({container.short_id}) from {args.image}")
return 0
except APIError as e:
return handle_api_error(e)
# --------------- CLI setup ---------------
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="dockermgr",
description="Simple Docker management and deployment CLI.",
)
subparsers = parser.add_subparsers(dest="command", help="Subcommand to run")
# list
p_list = subparsers.add_parser("list", help="List containers")
p_list.add_argument("-a", "--all", action="store_true", help="Show all containers (default shows running)")
p_list.set_defaults(func=cmd_list)
# images
p_images = subparsers.add_parser("images", help="List Docker images")
p_images.set_defaults(func=cmd_images)
# build
p_build = subparsers.add_parser("build", help="Build a Docker image")
p_build.add_argument("path", help="Build context (directory with Dockerfile)")
p_build.add_argument("-t", "--tag", required=True, help="Image tag, e.g. myapp:latest")
p_build.add_argument("-f", "--dockerfile", default="Dockerfile", help="Dockerfile name (default: Dockerfile)")
p_build.add_argument("--pull", action="store_true", help="Always attempt to pull newer base images")
p_build.set_defaults(func=cmd_build)
# run
p_run = subparsers.add_parser("run", help="Run a container")
p_run.add_argument("image", help="Image to run, e.g. myapp:latest")
p_run.add_argument("-n", "--name", help="Container name")
p_run.add_argument("-p", "--port", action="append", default=[],
help="Port mapping HOST:CONTAINER (can be used multiple times)")
p_run.add_argument("-e", "--env", action="append", default=[],
help="Environment variable KEY=VALUE (can be used multiple times)")
p_run.add_argument("-d", "--detach", action="store_true",
help="Run container in background (default: attached)")
p_run.add_argument("--restart", choices=["no", "on-failure", "always", "unless-stopped"],
help="Restart policy")
p_run.set_defaults(func=cmd_run)
# stop
p_stop = subparsers.add_parser("stop", help="Stop container(s)")
p_stop.add_argument("containers", nargs="+", help="Container name(s) or ID(s)")
p_stop.add_argument("-t", "--timeout", type=int, default=10,
help="Seconds to wait 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("containers", nargs="+", help="Container name(s) or ID(s)")
p_rm.add_argument("-f", "--force", action="store_true", help="Force remove (stop if running)")
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", type=int, default=100, help="Number of lines from the end (default: 100)")
p_logs.set_defaults(func=cmd_logs)
# deploy
p_deploy = subparsers.add_parser(
"deploy",
help="Deploy an image: pull (unless --no-pull), replace existing container with same name",
)
p_deploy.add_argument("-i", "--image", required=True, help="Image to deploy, e.g. myapp:latest")
p_deploy.add_argument("-n", "--name", required=True, help="Container name to (re)deploy")
p_deploy.add_argument("-p", "--port", action="append", default=[],
help="Port mapping HOST:CONTAINER (can be used multiple times)")
p_deploy.add_argument("-e", "--env", action="append", default=[],
help="Environment variable KEY=VALUE (can be used multiple times)")
p_deploy.add_argument("--restart", choices=["no", "on-failure", "always", "unless-stopped"],
default="unless-stopped", help="Restart policy (default: unless-stopped)")
p_deploy.add_argument("--no-pull", action="store_true", help="Do not pull image before deploying")
p_deploy.add_argument("-t", "--timeout", type=int, default=10,
help="Seconds to wait when stopping old container (default: 10)")
p_deploy.set_defaults(func=cmd_deploy)
return parser
def main(argv: Optional[List[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if not hasattr(args, "func"):
parser.print_help()
return 1
return args.func(args)
if __name__ == "__main__":
sys.exit(main())