CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-on-whales

A Docker client for Python, designed to be fun and intuitive!

Pending
Overview
Eval results
Files

service.mddocs/

Service Management

Docker swarm service management for running and orchestrating containerized applications across multiple nodes. Services define the desired state for long-running applications with automatic scaling, rolling updates, and health monitoring.

Capabilities

Service Creation

Create services with comprehensive configuration options.

def create(
    image: str,
    command: Optional[List[str]] = None,
    *,
    configs: Optional[List[str]] = None,
    constraints: Optional[List[str]] = None,
    container_labels: Optional[Dict[str, str]] = None,
    dns: Optional[List[str]] = None,
    dns_options: Optional[List[str]] = None,
    dns_search: Optional[List[str]] = None,
    endpoint_mode: Optional[str] = None,
    entrypoint: Optional[str] = None,
    envs: Optional[Dict[str, str]] = None,
    env_files: Optional[List[str]] = None,
    generic_resources: Optional[List[str]] = None,
    groups: Optional[List[str]] = None,
    healthcheck: bool = True,
    health_cmd: Optional[str] = None,
    health_interval: Optional[str] = None,
    health_retries: Optional[int] = None,
    health_start_period: Optional[str] = None,
    health_timeout: Optional[str] = None,
    hostname: Optional[str] = None,
    hosts: Optional[List[str]] = None,
    init: bool = False,
    isolation: Optional[str] = None,
    labels: Optional[Dict[str, str]] = None,
    limit_cpu: Optional[float] = None,
    limit_memory: Optional[str] = None,
    limit_pids: Optional[int] = None,
    log_driver: Optional[str] = None,
    log_options: Optional[Dict[str, str]] = None,
    max_concurrent: Optional[int] = None,
    mounts: Optional[List[str]] = None,
    name: Optional[str] = None,
    networks: Optional[List[str]] = None,
    no_healthcheck: bool = False,
    no_resolve_image: bool = False,
    placement_preferences: Optional[List[str]] = None,
    publish: Optional[List[str]] = None,
    quiet: bool = False,
    read_only: bool = False,
    replicas: Optional[int] = None,
    replicas_max_per_node: Optional[int] = None,
    reserve_cpu: Optional[float] = None,
    reserve_memory: Optional[str] = None,
    restart_condition: Optional[str] = None,
    restart_delay: Optional[str] = None,
    restart_max_attempts: Optional[int] = None,
    restart_window: Optional[str] = None,
    rollback_delay: Optional[str] = None,
    rollback_failure_action: Optional[str] = None,
    rollback_max_failure_ratio: Optional[float] = None,
    rollback_monitor: Optional[str] = None,
    rollback_order: Optional[str] = None,
    rollback_parallelism: Optional[int] = None,
    secrets: Optional[List[str]] = None,
    stop_grace_period: Optional[str] = None,
    stop_signal: Optional[str] = None,
    tty: bool = False,
    update_delay: Optional[str] = None,
    update_failure_action: Optional[str] = None,
    update_max_failure_ratio: Optional[float] = None,
    update_monitor: Optional[str] = None,
    update_order: Optional[str] = None,
    update_parallelism: Optional[int] = None,
    user: Optional[str] = None,
    with_registry_authentication: bool = False,
    workdir: Optional[str] = None
) -> Service:
    """
    Create a service with extensive configuration options.
    
    Parameters:
    - image: Container image to use
    - command: Command to run in containers
    - configs: Configuration objects to mount
    - constraints: Placement constraints
    - container_labels: Labels for containers
    - dns: DNS servers
    - dns_options: DNS options
    - dns_search: DNS search domains
    - endpoint_mode: Endpoint mode (vip or dnsrr)
    - entrypoint: Override image entrypoint
    - envs: Environment variables
    - env_files: Environment files
    - generic_resources: Generic resources
    - groups: Additional groups for user
    - healthcheck: Enable container healthcheck
    - health_cmd: Healthcheck command
    - health_interval: Interval between healthchecks
    - health_retries: Consecutive failures needed to report unhealthy
    - health_start_period: Grace period before healthchecks count
    - health_timeout: Maximum time for healthcheck
    - hostname: Container hostname
    - hosts: Additional host mappings
    - init: Use init inside containers
    - isolation: Container isolation technology
    - labels: Service labels
    - limit_cpu: CPU limit per container
    - limit_memory: Memory limit per container
    - limit_pids: Process limit per container
    - log_driver: Logging driver
    - log_options: Logging driver options
    - max_concurrent: Maximum concurrent operations during updates
    - mounts: Mount specifications
    - name: Service name
    - networks: Networks to connect
    - no_healthcheck: Disable healthcheck
    - no_resolve_image: Don't query registry for image digest
    - placement_preferences: Placement preferences
    - publish: Port mappings
    - quiet: Suppress progress output
    - read_only: Mount root filesystem as read-only
    - replicas: Number of replicas
    - replicas_max_per_node: Maximum replicas per node
    - reserve_cpu: Reserved CPU per container
    - reserve_memory: Reserved memory per container
    - restart_condition: Restart condition (none, on-failure, any)
    - restart_delay: Delay between restart attempts
    - restart_max_attempts: Maximum restart attempts
    - restart_window: Window for restart attempts
    - rollback_delay: Delay between rollback tasks
    - rollback_failure_action: Action on rollback failure
    - rollback_max_failure_ratio: Maximum failure ratio for rollback
    - rollback_monitor: Duration to monitor rollback
    - rollback_order: Rollback order (start-first or stop-first)
    - rollback_parallelism: Maximum rollback tasks in parallel
    - secrets: Secret objects to mount
    - stop_grace_period: Grace period before force-killing containers
    - stop_signal: Signal to stop containers
    - tty: Allocate pseudo-TTY
    - update_delay: Delay between update tasks
    - update_failure_action: Action on update failure
    - update_max_failure_ratio: Maximum failure ratio for updates
    - update_monitor: Duration to monitor updates
    - update_order: Update order (start-first or stop-first)
    - update_parallelism: Maximum update tasks in parallel
    - user: Username or UID
    - with_registry_authentication: Use registry authentication
    - workdir: Working directory
    
    Returns:
    Service object
    """

Service Information and Monitoring

Inspect services and list service tasks.

def inspect(x: Union[str, List[str]]) -> Union[Service, List[Service]]:
    """
    Inspect one or more services.
    
    Parameters:
    - x: Service name(s) or ID(s)
    
    Returns:
    Service object(s) with detailed information
    """

def exists(x: Union[str, Service]) -> bool:
    """
    Check if a service exists.
    
    Parameters:
    - x: Service name/ID or Service object
    
    Returns:
    True if service exists, False otherwise
    """

def list(filters: Sequence[str] = ()) -> List[Service]:
    """
    List services with optional filters.
    
    Parameters:
    - filters: Filter conditions
    
    Returns:
    List of Service objects
    """

def ps(x: Union[str, List[str]]) -> List[Task]:
    """
    List tasks for services.
    
    Parameters:
    - x: Service name(s) or ID(s)
    
    Returns:
    List of Task objects
    """

Service Logs

Get service logs with streaming support.

def logs(
    service: Union[str, Service],
    *,
    details: bool = False,
    follow: bool = False,
    no_resolve: bool = False,
    no_task_ids: bool = False,
    no_trunc: bool = False,
    raw: bool = False,
    since: Optional[str] = None,
    tail: Optional[int] = None,
    timestamps: bool = False,
    until: Optional[str] = None,
    stream: bool = False
) -> Union[str, Iterable[Tuple[str, bytes]]]:
    """
    Get service logs with comprehensive options.
    
    Parameters:
    - service: Service name/ID or Service object
    - details: Show extra details
    - follow: Follow log output
    - no_resolve: Don't resolve IDs to names
    - no_task_ids: Don't include task IDs
    - no_trunc: Don't truncate output
    - raw: Don't neatly format logs
    - since: Show logs since timestamp/duration
    - tail: Number of lines from end
    - timestamps: Show timestamps
    - until: Show logs until timestamp
    - stream: Return streaming iterator
    
    Returns:
    Log output as string or streaming iterator
    """

Service Updates and Scaling

Update service configuration and scale replicas.

def update(
    service: Union[str, Service],
    *,
    detach: bool = False,
    force: bool = False,
    image: Optional[str] = None,
    with_registry_authentication: bool = False,
    quiet: bool = False,
    replicas: Optional[int] = None,
    **kwargs
) -> None:
    """
    Update service configuration.
    
    Parameters:
    - service: Service name/ID or Service object
    - detach: Exit immediately instead of waiting
    - force: Force update even if no changes
    - image: Update to new image
    - with_registry_authentication: Use registry authentication
    - quiet: Suppress progress output
    - replicas: Number of replicas
    - **kwargs: Additional update options (same as create)
    """

def scale(new_scales: Dict[str, int], detach: bool = False) -> None:
    """
    Scale multiple services.
    
    Parameters:
    - new_scales: Mapping of service names to replica counts
    - detach: Exit immediately instead of waiting
    """

Service Removal

Remove services from the swarm.

def remove(services: Union[str, List[str]]) -> None:
    """
    Remove one or more services.
    
    Parameters:
    - services: Service name(s) or ID(s)
    """

Usage Examples:

from python_on_whales import docker

# Create a web service
service = docker.service.create(
    "nginx:alpine",
    name="web-server",
    replicas=3,
    publish=["80:80"],
    labels={"app": "web", "environment": "production"},
    constraints=["node.role==worker"],
    update_parallelism=1,
    update_delay="10s"
)

# Scale service
docker.service.scale({"web-server": 5})

# Update service with new image
docker.service.update(
    "web-server",
    image="nginx:1.21-alpine",
    with_registry_authentication=True
)

# Get service logs
logs = docker.service.logs("web-server", follow=True, stream=True)
for source, line in logs:
    print(f"{source}: {line.decode()}")

# List service tasks
tasks = docker.service.ps("web-server")
for task in tasks:
    print(f"Task: {task.name} - Node: {task.node_id} - State: {task.desired_state}")

Types

class Service:
    id: str
    version: DockerObjectVersion
    created_at: datetime
    updated_at: datetime
    spec: ServiceSpec
    previous_spec: Optional[ServiceSpec]
    endpoint: ServiceEndpoint
    update_status: Optional[ServiceUpdateStatus]
    
    def ps(self) -> List[Task]:
        """List tasks for this service."""
    
    def remove(self) -> None:
        """Remove this service."""
    
    def scale(self, new_scale: int, detach: bool = False) -> None:
        """Scale this service."""
    
    def update(
        self,
        detach: bool = False,
        force: bool = False,
        image: Optional[str] = None,
        with_registry_authentication: bool = False,
        quiet: bool = False,
        replicas: Optional[int] = None,
        **kwargs
    ) -> None:
        """Update this service."""
    
    def exists(self) -> bool:
        """Check if this service exists."""

class ServiceSpec:
    name: str
    labels: Dict[str, str]
    task_template: TaskSpec
    mode: ServiceMode
    update_config: Optional[UpdateConfig]
    rollback_config: Optional[UpdateConfig]
    networks: List[NetworkAttachmentConfig]
    endpoint_spec: Optional[EndpointSpec]

class ServiceEndpoint:
    spec: EndpointSpec
    ports: List[PortConfig]
    virtual_ips: List[Dict[str, Any]]

class ServiceUpdateStatus:
    state: str
    started_at: Optional[datetime]
    completed_at: Optional[datetime]
    message: Optional[str]

class TaskSpec:
    container_spec: ContainerSpec
    resources: Optional[ResourceRequirements]
    restart_policy: Optional[RestartPolicy]
    placement: Optional[Placement]
    log_driver: Optional[LogDriver]
    networks: List[NetworkAttachmentConfig]
    force_update: int

class ServiceMode:
    replicated: Optional[ReplicatedService]
    global_mode: Optional[Dict[str, Any]]

class ReplicatedService:
    replicas: Optional[int]

class UpdateConfig:
    parallelism: int
    delay: Optional[str]
    failure_action: str
    monitor: Optional[str]
    max_failure_ratio: Optional[float]
    order: str

class EndpointSpec:
    mode: str
    ports: List[PortConfig]

class PortConfig:
    name: Optional[str]
    protocol: str
    target_port: int
    published_port: Optional[int]
    publish_mode: str

Install with Tessl CLI

npx tessl i tessl/pypi-python-on-whales

docs

build.md

client.md

compose.md

config.md

containers.md

context.md

images.md

index.md

manifest.md

networks.md

node.md

plugin.md

pod.md

secret.md

service.md

stack.md

swarm.md

system.md

task.md

trust.md

volumes.md

tile.json