Skip to content

Stack

Profiles and environments

Set Compose profiles and interpolation files once on the stack; they apply to all its Compose operations. For example, select the environment before creating the stack:

import os
from orche import Stack

environment = os.environ.get("ORCHE_ENV", "dev")
if environment not in {"dev", "prod"}:
    raise ValueError(f"Unknown environment: {environment}")

stack = Stack(
    path=".",
    profiles=["debug"] if environment == "dev" else [],
    env_files=[".env", f".env.{environment}"],
)

Run with ORCHE_ENV=prod orche up. Relative env file paths are resolved against Stack.path; explicit files must exist when the stack is created. Compose reads the files in order, with later files overriding earlier ones. Shell variables take precedence for Compose interpolation. When no env files are supplied, Compose's normal default .env behavior applies. These are Compose CLI interpolation files, distinct from a service's env_file setting. See the Docker Compose interpolation documentation.

Main orchestrator for Docker Compose stacks.

Source code in orche/stack.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
class Stack:
    """Main orchestrator for Docker Compose stacks."""

    def __init__(
        self,
        name: str | None = None,
        path: str | Path = ".",
        compose_files: list[str] | list[Path] | None = None,
        host: str | None = None,
        profiles: list[str] | None = None,
        env_files: list[str | Path] | None = None,
    ):
        """Initialize a Docker Compose stack.

        Args:
            name: Optional project name (defaults to directory name)
            path: Project root path (defaults to current directory)
            compose_files: List of docker-compose file paths
                          (relative to project path or abs).
                          Files are merged in order (later files override earlier ones).
                          Defaults to ["docker-compose.yml"] if None.
                          Cannot be an empty list.
            host: Host name or IP used to build the URLs in
                  ``print_services_summary``. When omitted, the local outbound
                  IPv4 address is detected, falling back to ``127.0.0.1``.
            profiles: Compose profiles to enable for every operation.
            env_files: Ordered Compose interpolation env files, relative to
                the project path or absolute. Later files override earlier ones.

        Raises:
            ConfigError: If compose_files is empty or a specified file is missing
        """
        self.project_path: Path = Path(path).resolve()
        self.project_name = name
        self.host = host
        self.logger = get_logger()

        compose_file_inputs = (
            ["docker-compose.yml"] if compose_files is None else compose_files
        )
        if not compose_file_inputs:
            raise ConfigError(
                "compose_files cannot be an empty list. "
                "Either omit the parameter to use the default ['docker-compose.yml'], "
                "or provide at least one compose file path."
            )

        self.compose_files = [
            (cf if cf.is_absolute() else self.project_path / cf).resolve()
            for cf in (Path(item) for item in compose_file_inputs)
        ]

        # Validate all compose files exist
        missing_files = [cf for cf in self.compose_files if not cf.exists()]
        if missing_files:
            files_str = "\n  ".join(str(f) for f in missing_files)
            raise ConfigError(
                f"Docker Compose file(s) not found:\n  {files_str}\n"
                f"Please ensure the file(s) exist or provide the correct path(s)."
            )

        self.profiles = list(profiles or [])
        self.env_files = [
            (p if p.is_absolute() else self.project_path / p).resolve()
            for p in (Path(item) for item in (env_files or []))
        ]
        missing_env_files = [p for p in self.env_files if not p.is_file()]
        if missing_env_files:
            files_str = "\n  ".join(str(p) for p in missing_env_files)
            raise ConfigError(
                f"Environment file(s) not found or not files:\n  {files_str}"
            )

        # Initialize Docker wrapper
        self._docker = DockerComposeWrapper(
            compose_files=self.compose_files,
            project_name=self.project_name,
            project_path=self.project_path,
            profiles=self.profiles,
            env_files=self.env_files,
        )

        # Command registry
        self.commands: CommandRegistry[Callable[..., None]] = CommandRegistry()

        # Scoped to run() and isolated per thread/task, so concurrent or nested
        # runs on the same Stack never see each other's services.
        self._active_services_var: ContextVar[list[str] | None] = ContextVar(
            "orche_active_services", default=None
        )

    @property
    def _active_services(self) -> list[str]:
        return self._active_services_var.get() or []

    @_active_services.setter
    def _active_services(self, services: list[str]) -> None:
        self._active_services_var.set(services)

    def on(self, services: str | list[str]) -> bool:
        """Return True if at least one of the specified services is active.

        This method uses OR logic across the provided service names and checks
        membership against the current execution context (``self._active_services``).

        Args:
            services: A service name or list of service names to check.

        Returns:
            True if any of the specified services are active, False otherwise.
        """
        # Convert single service string to list
        if isinstance(services, str):
            services = [services]

        # If no services specified via CLI, all services are active
        if not self._active_services:
            return True

        # Check if any service in the list is active (OR logic)
        return any(s in self._active_services for s in services)

    def _resolve_services(
        self, services: list[str] | None, action: str
    ) -> list[str] | None:
        """Pick explicit services or the CLI-active ones, and log the action.

        Returns None when no services are targeted, which means "all services"
        to the Docker wrapper.
        """
        target_services = services if services is not None else self._active_services

        if target_services:
            self.logger.info(f"{action} services: {', '.join(target_services)}")
        else:
            self.logger.info(f"{action} all services")

        return target_services or None

    def build(self, services: list[str] | None = None) -> "Stack":
        """Build services in the stack.

        If 'services' is not provided, uses the active services from CLI args.

        Args:
            services: Optional list of specific services to build

        Returns:
            Self for method chaining
        """
        target_services = self._resolve_services(services, "Building")
        self._docker.build(services=target_services)
        return self

    def up(self, services: list[str] | None = None, wait: bool = True) -> "Stack":
        """Start services in the stack.

        If 'services' is not provided, uses the active services from CLI args.

        Args:
            services: Optional list of specific services to start
            wait: If True, wait for services to be running

        Returns:
            Self for method chaining
        """
        target_services = self._resolve_services(services, "Starting")
        self._docker.up(services=target_services, wait=wait)

        if wait:
            self.logger.info("Services are ready")

        return self

    def down(self, volumes: bool = False) -> "Stack":
        """Stop and remove the whole stack, including its networks.

        Like ``docker compose down``, this never targets specific services. Use
        :meth:`rm` for that.

        Args:
            volumes: Whether to remove named volumes

        Returns:
            Self for method chaining

        Raises:
            ConfigError: If services were selected on the command line
        """
        if self._active_services:
            raise ConfigError(
                "'down' acts on the whole stack and does not accept services "
                f"({', '.join(self._active_services)}). "
                "Use 'rm' to remove specific services."
            )
        self.logger.info("Stopping and removing all services")
        self._docker.down(volumes=volumes)
        return self

    def wait_for_service(
        self, service: str, timeout: float = 60, interval: float = 1
    ) -> "Stack":
        """Wait for every container of a service to be running and healthy.

        The service must define a healthcheck. Missing, starting and unhealthy
        containers are polled until the timeout; exited or dead containers and
        running containers without a healthcheck fail immediately.

        Args:
            service: Compose service name.
            timeout: Maximum polling time in seconds (positive and finite).
            interval: Delay between polls in seconds (positive and finite).

        Returns:
            Self for method chaining.

        Raises:
            ConfigError: If arguments are invalid.
            DockerComposeError: If inspection fails, a container cannot become
                healthy, or the timeout expires.
        """
        self._docker.wait_for_service(service, timeout=timeout, interval=interval)
        return self

    def rm(self, services: list[str] | None = None, volumes: bool = False) -> "Stack":
        """Stop and remove service containers, keeping networks and volumes.

        If 'services' is not provided, uses the active services from CLI args.

        Args:
            services: Optional list of specific services to remove
            volumes: Whether to remove anonymous volumes of the containers

        Returns:
            Self for method chaining
        """
        target_services = self._resolve_services(services, "Removing")
        self._docker.rm(services=target_services, volumes=volumes)
        return self

    def stop(self, services: list[str] | None = None) -> "Stack":
        """Stop services without removing them.

        Args:
            services: Optional list of specific services to stop

        Returns:
            Self for method chaining
        """
        target_services = self._resolve_services(services, "Stopping")
        self._docker.stop(services=target_services)
        return self

    def parse_args(
        self, command: str, tokens: list[str]
    ) -> tuple[list[str], dict[str, Any]]:
        """Split command-line tokens into service names and handler options.

        Options are the parameters of the command handler, so the handler's
        signature decides which tokens are option values and which are services.

        Args:
            command: Command name the tokens belong to.
            tokens: Everything that followed the command name.

        Returns:
            The service names and the resolved option values, defaults included.

        Raises:
            CommandError: If the command is unknown or the options are invalid.
        """
        specs = build_option_specs(self._get_handler(command))
        services, given = parse_tokens(command, specs, tokens)
        return services, complete_options(command, specs, given)

    def run(
        self,
        command: str,
        services: list[str] | None = None,
        options: dict[str, Any] | None = None,
    ) -> None:
        """Execute a command with before/after hooks.

        Execution order:
            1. Before-hooks run sequentially. First failure raises
               ``HookError`` and aborts (remaining hooks and handler are skipped).
            2. Main handler runs only if all before-hooks succeeded.
               Failures raise ``CommandError``; ``KeyboardInterrupt`` propagates.
            3. After-hooks run sequentially. First failure raises
               ``HookError`` and aborts (remaining after-hooks are skipped).

        Hooks receive only the options they declare as parameters.

        Args:
            command: Command name to execute.
            services: List of service names.
            options: Option values for the handler, keyed by parameter name.
                Omitted options take the handler's defaults.

        Raises:
            CommandError: If the command is not registered, the options are
                invalid, or the handler fails.
            HookError: If a before- or after-hook fails.
        """
        token = self._active_services_var.set(list(services or []))
        try:
            self._execute(command, options or {})
        finally:
            self._active_services_var.reset(token)

    def _get_handler(self, command: str) -> Callable[..., None]:
        handler = self.commands.get(command)
        if not handler:
            available = self.commands.available_commands()
            hint = (
                f" Available: {', '.join(available)}"
                if available
                else " No commands registered — did you forget @stack.commands.up?"
            )
            raise CommandError(f"Unknown command '{command}'.{hint}")
        return handler

    def _execute(self, command: str, options: dict[str, Any]) -> None:
        handler = self._get_handler(command)
        resolved = complete_options(command, build_option_specs(handler), options)

        for hook in self.commands.get_before_hooks(command):
            self._run_hook("before", command, hook, resolved)

        try:
            handler(**resolved)
        except Exception as e:
            raise CommandError(f"Command '{command}' failed: {e}") from e

        for hook in self.commands.get_after_hooks(command):
            self._run_hook("after", command, hook, resolved)

    @staticmethod
    def _run_hook(
        hook_type: str,
        command: str,
        hook: Callable[..., None],
        options: dict[str, Any],
    ) -> None:
        try:
            hook(**accepted_kwargs(hook, options))
        except Exception as e:
            raise HookError(hook_type, command, e) from e

    def client(self) -> DockerComposeWrapper:
        """Get the underlying DockerComposeWrapper instance."""
        return self._docker

    def print_services_summary(self) -> None:
        """Print a Rich panel listing running services and their local URLs."""
        containers = self._docker.ps()
        if not containers:
            return

        host = self.host or _get_local_ip()
        console = get_console()

        table = Table(
            show_header=True, header_style="bold cyan", box=None, padding=(0, 2)
        )
        table.add_column("Service", style="bold green")
        table.add_column("Container Port", style="yellow")
        table.add_column("URL", style="blue")

        seen: set[tuple[str, str, str]] = set()
        for container in containers:
            service = container.config.labels.get(
                "com.docker.compose.service", container.name
            )
            ports: dict = container.network_settings.ports or {}
            for container_port, bindings in ports.items():
                if not bindings:
                    continue
                for binding in bindings:
                    host_port = binding.get("HostPort", "")
                    if not host_port:
                        continue
                    key = (service, container_port, host_port)
                    if key in seen:
                        continue
                    seen.add(key)
                    port_number = container_port.split("/")[0]
                    scheme = "https" if port_number == "443" else "http"
                    table.add_row(
                        service,
                        container_port,
                        f"{scheme}://{host}:{host_port}",
                    )

        if table.row_count:
            console.print(
                Panel(table, title="[bold]Services[/bold]", border_style="cyan")
            )

__init__(name=None, path='.', compose_files=None, host=None, profiles=None, env_files=None)

Initialize a Docker Compose stack.

Parameters:

Name Type Description Default
name str | None

Optional project name (defaults to directory name)

None
path str | Path

Project root path (defaults to current directory)

'.'
compose_files list[str] | list[Path] | None

List of docker-compose file paths (relative to project path or abs). Files are merged in order (later files override earlier ones). Defaults to ["docker-compose.yml"] if None. Cannot be an empty list.

None
host str | None

Host name or IP used to build the URLs in print_services_summary. When omitted, the local outbound IPv4 address is detected, falling back to 127.0.0.1.

None
profiles list[str] | None

Compose profiles to enable for every operation.

None
env_files list[str | Path] | None

Ordered Compose interpolation env files, relative to the project path or absolute. Later files override earlier ones.

None

Raises:

Type Description
ConfigError

If compose_files is empty or a specified file is missing

Source code in orche/stack.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
def __init__(
    self,
    name: str | None = None,
    path: str | Path = ".",
    compose_files: list[str] | list[Path] | None = None,
    host: str | None = None,
    profiles: list[str] | None = None,
    env_files: list[str | Path] | None = None,
):
    """Initialize a Docker Compose stack.

    Args:
        name: Optional project name (defaults to directory name)
        path: Project root path (defaults to current directory)
        compose_files: List of docker-compose file paths
                      (relative to project path or abs).
                      Files are merged in order (later files override earlier ones).
                      Defaults to ["docker-compose.yml"] if None.
                      Cannot be an empty list.
        host: Host name or IP used to build the URLs in
              ``print_services_summary``. When omitted, the local outbound
              IPv4 address is detected, falling back to ``127.0.0.1``.
        profiles: Compose profiles to enable for every operation.
        env_files: Ordered Compose interpolation env files, relative to
            the project path or absolute. Later files override earlier ones.

    Raises:
        ConfigError: If compose_files is empty or a specified file is missing
    """
    self.project_path: Path = Path(path).resolve()
    self.project_name = name
    self.host = host
    self.logger = get_logger()

    compose_file_inputs = (
        ["docker-compose.yml"] if compose_files is None else compose_files
    )
    if not compose_file_inputs:
        raise ConfigError(
            "compose_files cannot be an empty list. "
            "Either omit the parameter to use the default ['docker-compose.yml'], "
            "or provide at least one compose file path."
        )

    self.compose_files = [
        (cf if cf.is_absolute() else self.project_path / cf).resolve()
        for cf in (Path(item) for item in compose_file_inputs)
    ]

    # Validate all compose files exist
    missing_files = [cf for cf in self.compose_files if not cf.exists()]
    if missing_files:
        files_str = "\n  ".join(str(f) for f in missing_files)
        raise ConfigError(
            f"Docker Compose file(s) not found:\n  {files_str}\n"
            f"Please ensure the file(s) exist or provide the correct path(s)."
        )

    self.profiles = list(profiles or [])
    self.env_files = [
        (p if p.is_absolute() else self.project_path / p).resolve()
        for p in (Path(item) for item in (env_files or []))
    ]
    missing_env_files = [p for p in self.env_files if not p.is_file()]
    if missing_env_files:
        files_str = "\n  ".join(str(p) for p in missing_env_files)
        raise ConfigError(
            f"Environment file(s) not found or not files:\n  {files_str}"
        )

    # Initialize Docker wrapper
    self._docker = DockerComposeWrapper(
        compose_files=self.compose_files,
        project_name=self.project_name,
        project_path=self.project_path,
        profiles=self.profiles,
        env_files=self.env_files,
    )

    # Command registry
    self.commands: CommandRegistry[Callable[..., None]] = CommandRegistry()

    # Scoped to run() and isolated per thread/task, so concurrent or nested
    # runs on the same Stack never see each other's services.
    self._active_services_var: ContextVar[list[str] | None] = ContextVar(
        "orche_active_services", default=None
    )

build(services=None)

Build services in the stack.

If 'services' is not provided, uses the active services from CLI args.

Parameters:

Name Type Description Default
services list[str] | None

Optional list of specific services to build

None

Returns:

Type Description
Stack

Self for method chaining

Source code in orche/stack.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def build(self, services: list[str] | None = None) -> "Stack":
    """Build services in the stack.

    If 'services' is not provided, uses the active services from CLI args.

    Args:
        services: Optional list of specific services to build

    Returns:
        Self for method chaining
    """
    target_services = self._resolve_services(services, "Building")
    self._docker.build(services=target_services)
    return self

client()

Get the underlying DockerComposeWrapper instance.

Source code in orche/stack.py
499
500
501
def client(self) -> DockerComposeWrapper:
    """Get the underlying DockerComposeWrapper instance."""
    return self._docker

down(volumes=False)

Stop and remove the whole stack, including its networks.

Like docker compose down, this never targets specific services. Use :meth:rm for that.

Parameters:

Name Type Description Default
volumes bool

Whether to remove named volumes

False

Returns:

Type Description
Stack

Self for method chaining

Raises:

Type Description
ConfigError

If services were selected on the command line

Source code in orche/stack.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
def down(self, volumes: bool = False) -> "Stack":
    """Stop and remove the whole stack, including its networks.

    Like ``docker compose down``, this never targets specific services. Use
    :meth:`rm` for that.

    Args:
        volumes: Whether to remove named volumes

    Returns:
        Self for method chaining

    Raises:
        ConfigError: If services were selected on the command line
    """
    if self._active_services:
        raise ConfigError(
            "'down' acts on the whole stack and does not accept services "
            f"({', '.join(self._active_services)}). "
            "Use 'rm' to remove specific services."
        )
    self.logger.info("Stopping and removing all services")
    self._docker.down(volumes=volumes)
    return self

on(services)

Return True if at least one of the specified services is active.

This method uses OR logic across the provided service names and checks membership against the current execution context (self._active_services).

Parameters:

Name Type Description Default
services str | list[str]

A service name or list of service names to check.

required

Returns:

Type Description
bool

True if any of the specified services are active, False otherwise.

Source code in orche/stack.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def on(self, services: str | list[str]) -> bool:
    """Return True if at least one of the specified services is active.

    This method uses OR logic across the provided service names and checks
    membership against the current execution context (``self._active_services``).

    Args:
        services: A service name or list of service names to check.

    Returns:
        True if any of the specified services are active, False otherwise.
    """
    # Convert single service string to list
    if isinstance(services, str):
        services = [services]

    # If no services specified via CLI, all services are active
    if not self._active_services:
        return True

    # Check if any service in the list is active (OR logic)
    return any(s in self._active_services for s in services)

parse_args(command, tokens)

Split command-line tokens into service names and handler options.

Options are the parameters of the command handler, so the handler's signature decides which tokens are option values and which are services.

Parameters:

Name Type Description Default
command str

Command name the tokens belong to.

required
tokens list[str]

Everything that followed the command name.

required

Returns:

Type Description
tuple[list[str], dict[str, Any]]

The service names and the resolved option values, defaults included.

Raises:

Type Description
CommandError

If the command is unknown or the options are invalid.

Source code in orche/stack.py
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
def parse_args(
    self, command: str, tokens: list[str]
) -> tuple[list[str], dict[str, Any]]:
    """Split command-line tokens into service names and handler options.

    Options are the parameters of the command handler, so the handler's
    signature decides which tokens are option values and which are services.

    Args:
        command: Command name the tokens belong to.
        tokens: Everything that followed the command name.

    Returns:
        The service names and the resolved option values, defaults included.

    Raises:
        CommandError: If the command is unknown or the options are invalid.
    """
    specs = build_option_specs(self._get_handler(command))
    services, given = parse_tokens(command, specs, tokens)
    return services, complete_options(command, specs, given)

print_services_summary()

Print a Rich panel listing running services and their local URLs.

Source code in orche/stack.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def print_services_summary(self) -> None:
    """Print a Rich panel listing running services and their local URLs."""
    containers = self._docker.ps()
    if not containers:
        return

    host = self.host or _get_local_ip()
    console = get_console()

    table = Table(
        show_header=True, header_style="bold cyan", box=None, padding=(0, 2)
    )
    table.add_column("Service", style="bold green")
    table.add_column("Container Port", style="yellow")
    table.add_column("URL", style="blue")

    seen: set[tuple[str, str, str]] = set()
    for container in containers:
        service = container.config.labels.get(
            "com.docker.compose.service", container.name
        )
        ports: dict = container.network_settings.ports or {}
        for container_port, bindings in ports.items():
            if not bindings:
                continue
            for binding in bindings:
                host_port = binding.get("HostPort", "")
                if not host_port:
                    continue
                key = (service, container_port, host_port)
                if key in seen:
                    continue
                seen.add(key)
                port_number = container_port.split("/")[0]
                scheme = "https" if port_number == "443" else "http"
                table.add_row(
                    service,
                    container_port,
                    f"{scheme}://{host}:{host_port}",
                )

    if table.row_count:
        console.print(
            Panel(table, title="[bold]Services[/bold]", border_style="cyan")
        )

rm(services=None, volumes=False)

Stop and remove service containers, keeping networks and volumes.

If 'services' is not provided, uses the active services from CLI args.

Parameters:

Name Type Description Default
services list[str] | None

Optional list of specific services to remove

None
volumes bool

Whether to remove anonymous volumes of the containers

False

Returns:

Type Description
Stack

Self for method chaining

Source code in orche/stack.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
def rm(self, services: list[str] | None = None, volumes: bool = False) -> "Stack":
    """Stop and remove service containers, keeping networks and volumes.

    If 'services' is not provided, uses the active services from CLI args.

    Args:
        services: Optional list of specific services to remove
        volumes: Whether to remove anonymous volumes of the containers

    Returns:
        Self for method chaining
    """
    target_services = self._resolve_services(services, "Removing")
    self._docker.rm(services=target_services, volumes=volumes)
    return self

run(command, services=None, options=None)

Execute a command with before/after hooks.

Execution order
  1. Before-hooks run sequentially. First failure raises HookError and aborts (remaining hooks and handler are skipped).
  2. Main handler runs only if all before-hooks succeeded. Failures raise CommandError; KeyboardInterrupt propagates.
  3. After-hooks run sequentially. First failure raises HookError and aborts (remaining after-hooks are skipped).

Hooks receive only the options they declare as parameters.

Parameters:

Name Type Description Default
command str

Command name to execute.

required
services list[str] | None

List of service names.

None
options dict[str, Any] | None

Option values for the handler, keyed by parameter name. Omitted options take the handler's defaults.

None

Raises:

Type Description
CommandError

If the command is not registered, the options are invalid, or the handler fails.

HookError

If a before- or after-hook fails.

Source code in orche/stack.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def run(
    self,
    command: str,
    services: list[str] | None = None,
    options: dict[str, Any] | None = None,
) -> None:
    """Execute a command with before/after hooks.

    Execution order:
        1. Before-hooks run sequentially. First failure raises
           ``HookError`` and aborts (remaining hooks and handler are skipped).
        2. Main handler runs only if all before-hooks succeeded.
           Failures raise ``CommandError``; ``KeyboardInterrupt`` propagates.
        3. After-hooks run sequentially. First failure raises
           ``HookError`` and aborts (remaining after-hooks are skipped).

    Hooks receive only the options they declare as parameters.

    Args:
        command: Command name to execute.
        services: List of service names.
        options: Option values for the handler, keyed by parameter name.
            Omitted options take the handler's defaults.

    Raises:
        CommandError: If the command is not registered, the options are
            invalid, or the handler fails.
        HookError: If a before- or after-hook fails.
    """
    token = self._active_services_var.set(list(services or []))
    try:
        self._execute(command, options or {})
    finally:
        self._active_services_var.reset(token)

stop(services=None)

Stop services without removing them.

Parameters:

Name Type Description Default
services list[str] | None

Optional list of specific services to stop

None

Returns:

Type Description
Stack

Self for method chaining

Source code in orche/stack.py
390
391
392
393
394
395
396
397
398
399
400
401
def stop(self, services: list[str] | None = None) -> "Stack":
    """Stop services without removing them.

    Args:
        services: Optional list of specific services to stop

    Returns:
        Self for method chaining
    """
    target_services = self._resolve_services(services, "Stopping")
    self._docker.stop(services=target_services)
    return self

up(services=None, wait=True)

Start services in the stack.

If 'services' is not provided, uses the active services from CLI args.

Parameters:

Name Type Description Default
services list[str] | None

Optional list of specific services to start

None
wait bool

If True, wait for services to be running

True

Returns:

Type Description
Stack

Self for method chaining

Source code in orche/stack.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
def up(self, services: list[str] | None = None, wait: bool = True) -> "Stack":
    """Start services in the stack.

    If 'services' is not provided, uses the active services from CLI args.

    Args:
        services: Optional list of specific services to start
        wait: If True, wait for services to be running

    Returns:
        Self for method chaining
    """
    target_services = self._resolve_services(services, "Starting")
    self._docker.up(services=target_services, wait=wait)

    if wait:
        self.logger.info("Services are ready")

    return self

wait_for_service(service, timeout=60, interval=1)

Wait for every container of a service to be running and healthy.

The service must define a healthcheck. Missing, starting and unhealthy containers are polled until the timeout; exited or dead containers and running containers without a healthcheck fail immediately.

Parameters:

Name Type Description Default
service str

Compose service name.

required
timeout float

Maximum polling time in seconds (positive and finite).

60
interval float

Delay between polls in seconds (positive and finite).

1

Returns:

Type Description
Stack

Self for method chaining.

Raises:

Type Description
ConfigError

If arguments are invalid.

DockerComposeError

If inspection fails, a container cannot become healthy, or the timeout expires.

Source code in orche/stack.py
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def wait_for_service(
    self, service: str, timeout: float = 60, interval: float = 1
) -> "Stack":
    """Wait for every container of a service to be running and healthy.

    The service must define a healthcheck. Missing, starting and unhealthy
    containers are polled until the timeout; exited or dead containers and
    running containers without a healthcheck fail immediately.

    Args:
        service: Compose service name.
        timeout: Maximum polling time in seconds (positive and finite).
        interval: Delay between polls in seconds (positive and finite).

    Returns:
        Self for method chaining.

    Raises:
        ConfigError: If arguments are invalid.
        DockerComposeError: If inspection fails, a container cannot become
            healthy, or the timeout expires.
    """
    self._docker.wait_for_service(service, timeout=timeout, interval=interval)
    return self