0
# Service Management
1
2
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.
3
4
## Capabilities
5
6
### Service Creation
7
8
Create services with comprehensive configuration options.
9
10
```python { .api }
11
def create(
12
image: str,
13
command: Optional[List[str]] = None,
14
*,
15
configs: Optional[List[str]] = None,
16
constraints: Optional[List[str]] = None,
17
container_labels: Optional[Dict[str, str]] = None,
18
dns: Optional[List[str]] = None,
19
dns_options: Optional[List[str]] = None,
20
dns_search: Optional[List[str]] = None,
21
endpoint_mode: Optional[str] = None,
22
entrypoint: Optional[str] = None,
23
envs: Optional[Dict[str, str]] = None,
24
env_files: Optional[List[str]] = None,
25
generic_resources: Optional[List[str]] = None,
26
groups: Optional[List[str]] = None,
27
healthcheck: bool = True,
28
health_cmd: Optional[str] = None,
29
health_interval: Optional[str] = None,
30
health_retries: Optional[int] = None,
31
health_start_period: Optional[str] = None,
32
health_timeout: Optional[str] = None,
33
hostname: Optional[str] = None,
34
hosts: Optional[List[str]] = None,
35
init: bool = False,
36
isolation: Optional[str] = None,
37
labels: Optional[Dict[str, str]] = None,
38
limit_cpu: Optional[float] = None,
39
limit_memory: Optional[str] = None,
40
limit_pids: Optional[int] = None,
41
log_driver: Optional[str] = None,
42
log_options: Optional[Dict[str, str]] = None,
43
max_concurrent: Optional[int] = None,
44
mounts: Optional[List[str]] = None,
45
name: Optional[str] = None,
46
networks: Optional[List[str]] = None,
47
no_healthcheck: bool = False,
48
no_resolve_image: bool = False,
49
placement_preferences: Optional[List[str]] = None,
50
publish: Optional[List[str]] = None,
51
quiet: bool = False,
52
read_only: bool = False,
53
replicas: Optional[int] = None,
54
replicas_max_per_node: Optional[int] = None,
55
reserve_cpu: Optional[float] = None,
56
reserve_memory: Optional[str] = None,
57
restart_condition: Optional[str] = None,
58
restart_delay: Optional[str] = None,
59
restart_max_attempts: Optional[int] = None,
60
restart_window: Optional[str] = None,
61
rollback_delay: Optional[str] = None,
62
rollback_failure_action: Optional[str] = None,
63
rollback_max_failure_ratio: Optional[float] = None,
64
rollback_monitor: Optional[str] = None,
65
rollback_order: Optional[str] = None,
66
rollback_parallelism: Optional[int] = None,
67
secrets: Optional[List[str]] = None,
68
stop_grace_period: Optional[str] = None,
69
stop_signal: Optional[str] = None,
70
tty: bool = False,
71
update_delay: Optional[str] = None,
72
update_failure_action: Optional[str] = None,
73
update_max_failure_ratio: Optional[float] = None,
74
update_monitor: Optional[str] = None,
75
update_order: Optional[str] = None,
76
update_parallelism: Optional[int] = None,
77
user: Optional[str] = None,
78
with_registry_authentication: bool = False,
79
workdir: Optional[str] = None
80
) -> Service:
81
"""
82
Create a service with extensive configuration options.
83
84
Parameters:
85
- image: Container image to use
86
- command: Command to run in containers
87
- configs: Configuration objects to mount
88
- constraints: Placement constraints
89
- container_labels: Labels for containers
90
- dns: DNS servers
91
- dns_options: DNS options
92
- dns_search: DNS search domains
93
- endpoint_mode: Endpoint mode (vip or dnsrr)
94
- entrypoint: Override image entrypoint
95
- envs: Environment variables
96
- env_files: Environment files
97
- generic_resources: Generic resources
98
- groups: Additional groups for user
99
- healthcheck: Enable container healthcheck
100
- health_cmd: Healthcheck command
101
- health_interval: Interval between healthchecks
102
- health_retries: Consecutive failures needed to report unhealthy
103
- health_start_period: Grace period before healthchecks count
104
- health_timeout: Maximum time for healthcheck
105
- hostname: Container hostname
106
- hosts: Additional host mappings
107
- init: Use init inside containers
108
- isolation: Container isolation technology
109
- labels: Service labels
110
- limit_cpu: CPU limit per container
111
- limit_memory: Memory limit per container
112
- limit_pids: Process limit per container
113
- log_driver: Logging driver
114
- log_options: Logging driver options
115
- max_concurrent: Maximum concurrent operations during updates
116
- mounts: Mount specifications
117
- name: Service name
118
- networks: Networks to connect
119
- no_healthcheck: Disable healthcheck
120
- no_resolve_image: Don't query registry for image digest
121
- placement_preferences: Placement preferences
122
- publish: Port mappings
123
- quiet: Suppress progress output
124
- read_only: Mount root filesystem as read-only
125
- replicas: Number of replicas
126
- replicas_max_per_node: Maximum replicas per node
127
- reserve_cpu: Reserved CPU per container
128
- reserve_memory: Reserved memory per container
129
- restart_condition: Restart condition (none, on-failure, any)
130
- restart_delay: Delay between restart attempts
131
- restart_max_attempts: Maximum restart attempts
132
- restart_window: Window for restart attempts
133
- rollback_delay: Delay between rollback tasks
134
- rollback_failure_action: Action on rollback failure
135
- rollback_max_failure_ratio: Maximum failure ratio for rollback
136
- rollback_monitor: Duration to monitor rollback
137
- rollback_order: Rollback order (start-first or stop-first)
138
- rollback_parallelism: Maximum rollback tasks in parallel
139
- secrets: Secret objects to mount
140
- stop_grace_period: Grace period before force-killing containers
141
- stop_signal: Signal to stop containers
142
- tty: Allocate pseudo-TTY
143
- update_delay: Delay between update tasks
144
- update_failure_action: Action on update failure
145
- update_max_failure_ratio: Maximum failure ratio for updates
146
- update_monitor: Duration to monitor updates
147
- update_order: Update order (start-first or stop-first)
148
- update_parallelism: Maximum update tasks in parallel
149
- user: Username or UID
150
- with_registry_authentication: Use registry authentication
151
- workdir: Working directory
152
153
Returns:
154
Service object
155
"""
156
```
157
158
### Service Information and Monitoring
159
160
Inspect services and list service tasks.
161
162
```python { .api }
163
def inspect(x: Union[str, List[str]]) -> Union[Service, List[Service]]:
164
"""
165
Inspect one or more services.
166
167
Parameters:
168
- x: Service name(s) or ID(s)
169
170
Returns:
171
Service object(s) with detailed information
172
"""
173
174
def exists(x: Union[str, Service]) -> bool:
175
"""
176
Check if a service exists.
177
178
Parameters:
179
- x: Service name/ID or Service object
180
181
Returns:
182
True if service exists, False otherwise
183
"""
184
185
def list(filters: Sequence[str] = ()) -> List[Service]:
186
"""
187
List services with optional filters.
188
189
Parameters:
190
- filters: Filter conditions
191
192
Returns:
193
List of Service objects
194
"""
195
196
def ps(x: Union[str, List[str]]) -> List[Task]:
197
"""
198
List tasks for services.
199
200
Parameters:
201
- x: Service name(s) or ID(s)
202
203
Returns:
204
List of Task objects
205
"""
206
```
207
208
### Service Logs
209
210
Get service logs with streaming support.
211
212
```python { .api }
213
def logs(
214
service: Union[str, Service],
215
*,
216
details: bool = False,
217
follow: bool = False,
218
no_resolve: bool = False,
219
no_task_ids: bool = False,
220
no_trunc: bool = False,
221
raw: bool = False,
222
since: Optional[str] = None,
223
tail: Optional[int] = None,
224
timestamps: bool = False,
225
until: Optional[str] = None,
226
stream: bool = False
227
) -> Union[str, Iterable[Tuple[str, bytes]]]:
228
"""
229
Get service logs with comprehensive options.
230
231
Parameters:
232
- service: Service name/ID or Service object
233
- details: Show extra details
234
- follow: Follow log output
235
- no_resolve: Don't resolve IDs to names
236
- no_task_ids: Don't include task IDs
237
- no_trunc: Don't truncate output
238
- raw: Don't neatly format logs
239
- since: Show logs since timestamp/duration
240
- tail: Number of lines from end
241
- timestamps: Show timestamps
242
- until: Show logs until timestamp
243
- stream: Return streaming iterator
244
245
Returns:
246
Log output as string or streaming iterator
247
"""
248
```
249
250
### Service Updates and Scaling
251
252
Update service configuration and scale replicas.
253
254
```python { .api }
255
def update(
256
service: Union[str, Service],
257
*,
258
detach: bool = False,
259
force: bool = False,
260
image: Optional[str] = None,
261
with_registry_authentication: bool = False,
262
quiet: bool = False,
263
replicas: Optional[int] = None,
264
**kwargs
265
) -> None:
266
"""
267
Update service configuration.
268
269
Parameters:
270
- service: Service name/ID or Service object
271
- detach: Exit immediately instead of waiting
272
- force: Force update even if no changes
273
- image: Update to new image
274
- with_registry_authentication: Use registry authentication
275
- quiet: Suppress progress output
276
- replicas: Number of replicas
277
- **kwargs: Additional update options (same as create)
278
"""
279
280
def scale(new_scales: Dict[str, int], detach: bool = False) -> None:
281
"""
282
Scale multiple services.
283
284
Parameters:
285
- new_scales: Mapping of service names to replica counts
286
- detach: Exit immediately instead of waiting
287
"""
288
```
289
290
### Service Removal
291
292
Remove services from the swarm.
293
294
```python { .api }
295
def remove(services: Union[str, List[str]]) -> None:
296
"""
297
Remove one or more services.
298
299
Parameters:
300
- services: Service name(s) or ID(s)
301
"""
302
```
303
304
**Usage Examples:**
305
306
```python
307
from python_on_whales import docker
308
309
# Create a web service
310
service = docker.service.create(
311
"nginx:alpine",
312
name="web-server",
313
replicas=3,
314
publish=["80:80"],
315
labels={"app": "web", "environment": "production"},
316
constraints=["node.role==worker"],
317
update_parallelism=1,
318
update_delay="10s"
319
)
320
321
# Scale service
322
docker.service.scale({"web-server": 5})
323
324
# Update service with new image
325
docker.service.update(
326
"web-server",
327
image="nginx:1.21-alpine",
328
with_registry_authentication=True
329
)
330
331
# Get service logs
332
logs = docker.service.logs("web-server", follow=True, stream=True)
333
for source, line in logs:
334
print(f"{source}: {line.decode()}")
335
336
# List service tasks
337
tasks = docker.service.ps("web-server")
338
for task in tasks:
339
print(f"Task: {task.name} - Node: {task.node_id} - State: {task.desired_state}")
340
```
341
342
## Types
343
344
```python { .api }
345
class Service:
346
id: str
347
version: DockerObjectVersion
348
created_at: datetime
349
updated_at: datetime
350
spec: ServiceSpec
351
previous_spec: Optional[ServiceSpec]
352
endpoint: ServiceEndpoint
353
update_status: Optional[ServiceUpdateStatus]
354
355
def ps(self) -> List[Task]:
356
"""List tasks for this service."""
357
358
def remove(self) -> None:
359
"""Remove this service."""
360
361
def scale(self, new_scale: int, detach: bool = False) -> None:
362
"""Scale this service."""
363
364
def update(
365
self,
366
detach: bool = False,
367
force: bool = False,
368
image: Optional[str] = None,
369
with_registry_authentication: bool = False,
370
quiet: bool = False,
371
replicas: Optional[int] = None,
372
**kwargs
373
) -> None:
374
"""Update this service."""
375
376
def exists(self) -> bool:
377
"""Check if this service exists."""
378
379
class ServiceSpec:
380
name: str
381
labels: Dict[str, str]
382
task_template: TaskSpec
383
mode: ServiceMode
384
update_config: Optional[UpdateConfig]
385
rollback_config: Optional[UpdateConfig]
386
networks: List[NetworkAttachmentConfig]
387
endpoint_spec: Optional[EndpointSpec]
388
389
class ServiceEndpoint:
390
spec: EndpointSpec
391
ports: List[PortConfig]
392
virtual_ips: List[Dict[str, Any]]
393
394
class ServiceUpdateStatus:
395
state: str
396
started_at: Optional[datetime]
397
completed_at: Optional[datetime]
398
message: Optional[str]
399
400
class TaskSpec:
401
container_spec: ContainerSpec
402
resources: Optional[ResourceRequirements]
403
restart_policy: Optional[RestartPolicy]
404
placement: Optional[Placement]
405
log_driver: Optional[LogDriver]
406
networks: List[NetworkAttachmentConfig]
407
force_update: int
408
409
class ServiceMode:
410
replicated: Optional[ReplicatedService]
411
global_mode: Optional[Dict[str, Any]]
412
413
class ReplicatedService:
414
replicas: Optional[int]
415
416
class UpdateConfig:
417
parallelism: int
418
delay: Optional[str]
419
failure_action: str
420
monitor: Optional[str]
421
max_failure_ratio: Optional[float]
422
order: str
423
424
class EndpointSpec:
425
mode: str
426
ports: List[PortConfig]
427
428
class PortConfig:
429
name: Optional[str]
430
protocol: str
431
target_port: int
432
published_port: Optional[int]
433
publish_mode: str
434
```