A Docker client for Python, designed to be fun and intuitive!
—
Docker stack management for deploying multi-service applications using Docker Compose files in swarm mode. Stacks provide a way to manage complex applications as a single unit with shared networks, volumes, and configurations.
Deploy stacks from Docker Compose files with environment variable support.
def deploy(
name: str,
compose_files: List[str],
*,
orchestrator: Optional[str] = None,
prune: bool = False,
resolve_image: str = "always",
with_registry_auth: bool = False,
env_files: Optional[List[str]] = None,
variables: Optional[Dict[str, str]] = None
) -> None:
"""
Deploy a stack from compose files.
Parameters:
- name: Stack name
- compose_files: List of Docker Compose files
- orchestrator: Orchestrator to use (swarm/kubernetes)
- prune: Prune services no longer referenced
- resolve_image: Image resolution (always/changed/never)
- with_registry_auth: Use registry authentication
- env_files: Environment files to load
- variables: Environment variables to set
"""List stacks and inspect stack components.
def list() -> List[Stack]:
"""
List all stacks.
Returns:
List of Stack objects
"""
def services(stack: Union[str, Stack]) -> List[Service]:
"""
List services in a stack.
Parameters:
- stack: Stack name or Stack object
Returns:
List of Service objects
"""
def ps(x: Union[str, Stack]) -> List[Task]:
"""
List tasks in a stack.
Parameters:
- x: Stack name or Stack object
Returns:
List of Task objects
"""Remove stacks and their associated resources.
def remove(x: Union[str, List[str]]) -> None:
"""
Remove one or more stacks.
Parameters:
- x: Stack name(s) to remove
"""Usage Examples:
from python_on_whales import docker
# Deploy stack from compose file
docker.stack.deploy(
"my-app-stack",
["docker-compose.yml", "docker-compose.prod.yml"],
env_files=[".env.prod"],
variables={"REPLICAS": "3", "IMAGE_TAG": "v1.2.0"},
with_registry_auth=True
)
# List all stacks
stacks = docker.stack.list()
for stack in stacks:
print(f"Stack: {stack.name} - Services: {len(stack.services())}")
# Get stack services
services = docker.stack.services("my-app-stack")
for service in services:
print(f"Service: {service.spec.name} - Replicas: {service.spec.mode.replicated.replicas}")
# Get stack tasks
tasks = docker.stack.ps("my-app-stack")
for task in tasks:
print(f"Task: {task.name} - State: {task.desired_state} - Node: {task.node_id}")
# Remove stack
docker.stack.remove("my-app-stack")class Stack:
name: str
services: int
orchestrator: str
namespace: str
def remove(self) -> None:
"""Remove this stack."""
def ps(self) -> List[Task]:
"""List tasks in this stack."""
def services(self) -> List[Service]:
"""List services in this stack."""Install with Tessl CLI
npx tessl i tessl/pypi-python-on-whales