Support health condition for container dependencies (--requires)
Feature request description
Environment OS: CentOS Stream 10 Podman: 6.1.0 podman-compose: 1.5.0 Rootful Podman Problem
Podman supports persistent container dependencies using --requires.
For example, podman-compose translates:
depends_on: db: condition: service_healthy
into:
podman create ... --requires=db ...
The dependency is stored by Podman:
"Dependencies": [
"
However, the healthy condition is not stored.
As a result, after a reboot:
podman start --all
Podman starts the required container first, but does not wait for it to become healthy before starting the dependent container.
Suggest potential solution
Suggestion
Could Podman support an optional condition for --requires, for example by storing additional dependency metadata?
Conceptually:
requires: db condition: healthy
If the condition is missing, behavior remains exactly as today (started), so this should be backward compatible.
If the condition is healthy, podman start / podman start --all would:
start db wait for db to become healthy start dependent container
This would also allow Compose implementations to preserve depends_on: condition: service_healthy after the initial compose up.
Have you considered any alternatives?
A clear and concise description of any alternative solutions or features you've considered.
Additional context
Add any other context or screenshots about the feature request here.
Hi @harryzz and maintainers!
I'd like to take this on. I did a code walkthrough of the creation, storage, and start paths and would love to validate the design with you before putting up a PR.
1. CLI & SpecGen Syntax
Extend --requires values with an optional :condition suffix, following the same colon-split precedent used in --network name:ip=... (pkg/specgen/namespaces.go):
- Syntax:
--requires <name>[:condition] - Supported conditions:
started(default, preserves existing behavior) andhealthy. - Comma separation works out of the box with Cobra's
StringSliceVar:--requires db:healthy,cache:started. - Remote API / SpecGen: parse this in
specgenutiland propagate toSpecGenerator.DependencyContainers(or dedicated dependency spec).
2. Storage & Backwards Compatibility (Additive)
To keep the SQLite relational integrity table (ContainerDependency(ID, DependencyID)) untouched and avoid breaking older container configs, preserve ContainerConfig.Dependencies []string (libpod/container_config.go:81) as-is for the dependency IDs.
Add a parallel field to ContainerConfig:
// DependencyConditions maps a dependency container ID to the condition
// required before this container can start. Absent entries default to "started".
DependencyConditions map[string]string `json:"dependencyConditions,omitempty"`
Hi @i-OmSharma — thanks for picking this up!
Your --requires db:healthy syntax is a natural fit — it mirrors the Docker Compose V2 depends_on: condition: service_healthy convention directly at the Podman CLI level, which makes it the right direction for upstream.
For reference: I've already implemented and tested a working experimental version of this on CentOS Stream 10 aarch64 (two hosts, running in production). My approach was intentionally minimal — no CLI change — using a container label (io.podman.compose.requires-healthy.v1) set by patched podman-compose, with a new libpod/container_dependency_health.go reading it on start. No ContainerConfig or specgen changes, no DB migration.
That file might be useful as a reference when you implement the healthy-wait logic.
Happy to share the patches if they'd help.
Here are the patches for reference. Sources are the installed SRPMs on CentOS Stream 10:
podman-6.1.0-2.el10.src.rpm(upstream commitcade97a52ebdf9dbf9e81de8009015776837a074)podman-compose-1.5.0-1.el10_1.src.rpm(EPEL)
Podman patch (podman-healthy-dependencies.patch):
--- a/libpod/container_internal.go
+++ b/libpod/container_internal.go
@@ -836,6 +836,9 @@
return err
}
}
+ if err := c.waitForHealthyDependencies(ctx); err != nil {
+ return err
+ }
defer func() {
if retErr != nil {
@@ -1217,6 +1220,9 @@
// If we are paused, throw an error
if c.state.State == define.ContainerStatePaused {
return fmt.Errorf("cannot start paused container %s: %w", c.ID(), define.ErrCtrStateInvalid)
+ }
+ if err := c.waitForHealthyDependencies(ctx); err != nil {
+ return err
}
defer func() {
--- /dev/null
+++ b/libpod/container_dependency_health.go
@@ -0,0 +1,67 @@
+//go:build !remote
+
+package libpod
+
+import (
+ "context"
+ "fmt"
+
+ "go.podman.io/podman/v6/libpod/define"
+)
+
+const healthyDependenciesLabel = "io.podman.compose.requires-healthy.v1"
+
+// waitForHealthyDependencies gates startup on optional Compose metadata without
+// changing the dependency graph. The caller holds c's lock; dependency locks are
+// acquired only by the existing state/health accessors, never across a wait.
+func (c *Container) waitForHealthyDependencies(ctx context.Context) error {
+ raw, present := c.config.Labels[healthyDependenciesLabel]
+ if !present {
+ return nil
+ }
+ var names []string
+ if err := json.Unmarshal([]byte(raw), &names); err != nil {
+ return fmt.Errorf("container %s: invalid %s: %w", c.ID(), healthyDependenciesLabel, err)
+ }
+ if names == nil {
+ return fmt.Errorf("container %s: %s must be a JSON array of container names", c.ID(), healthyDependenciesLabel)
+ }
+ if len(names) == 0 {
+ return nil
+ }
+
+ // Resolve names only within the existing ID-based dependency graph. A rename
+ // must fail closed instead of following a different container with that name.
+ dependencies := make(map[string]*Container)
+ for _, id := range c.Dependencies() {
+ dep, err := c.runtime.state.Container(id)
+ if err != nil {
+ return fmt.Errorf("retrieving dependency %s of container %s: %w", id, c.ID(), err)
+ }
+ dependencies[dep.Name()] = dep
+ }
+ for _, name := range names {
+ dep, found := dependencies[name]
+ if !found {
+ return fmt.Errorf("container %s: healthy dependency %q is not an existing dependency", c.ID(), name)
+ }
+ if !dep.HasHealthCheck() {
+ return fmt.Errorf("container %s: healthy dependency %q has no healthcheck", c.ID(), name)
+ }
+ }
+ for _, name := range names {
+ dep := dependencies[name]
+ if _, err := dep.WaitForConditionWithInterval(ctx, DefaultWaitInterval, define.HealthCheckHealthy); err != nil {
+ return fmt.Errorf("container %s: waiting for healthy dependency %q: %w", c.ID(), name, err)
+ }
+ // The generic health wait can observe a final healthy result after exit.
+ state, err := dep.State()
+ if err != nil {
+ return fmt.Errorf("container %s: checking healthy dependency %q: %w", c.ID(), name, err)
+ }
+ if state != define.ContainerStateRunning {
+ return fmt.Errorf("container %s: healthy dependency %q is not running: %w", c.ID(), name, define.ErrCtrStateInvalid)
+ }
+ }
+ return nil
+}
--- /dev/null
+++ b/libpod/container_dependency_health_test.go
@@ -0,0 +1,38 @@
+//go:build !remote
+
+package libpod
+
+import (
+ "context"
+ "strings"
+ "testing"
+)
+
+func TestHealthyDependencyMetadata(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ labels map[string]string
+ err string
+ }{
+ {name: "legacy"},
+ {name: "empty array", labels: map[string]string{healthyDependenciesLabel: "[]"}},
+ {name: "empty value", labels: map[string]string{healthyDependenciesLabel: ""}, err: "invalid"},
+ {name: "null", labels: map[string]string{healthyDependenciesLabel: "null"}, err: "JSON array"},
+ {name: "object", labels: map[string]string{healthyDependenciesLabel: "{}"}, err: "invalid"},
+ {name: "number", labels: map[string]string{healthyDependenciesLabel: "[1]"}, err: "invalid"},
+ {name: "extra dependency", labels: map[string]string{healthyDependenciesLabel: `["db"]`}, err: "not an existing dependency"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ ctr := &Container{config: &ContainerConfig{}}
+ ctr.config.Labels = test.labels
+ err := ctr.waitForHealthyDependencies(context.Background())
+ if test.err == "" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ } else if err == nil || !strings.Contains(err.Error(), test.err) {
+ t.Fatalf("expected error containing %q, got %v", test.err, err)
+ }
+ })
+ }
+}
podman-compose patch (compose-healthy-dependencies.patch):
--- a/podman_compose.py
+++ b/podman_compose.py
@@ -1115,6 +1115,19 @@
if deps and not no_deps:
deps_csv = ",".join(deps)
podman_args.append(f"--requires={deps_csv}")
+ # Persist direct health conditions; _deps also contains transitive edges.
+ healthy_deps = sorted({
+ name
+ for service, dependency in cnt.get("depends_on", {}).items()
+ if dependency.get("condition") == "service_healthy"
+ for name in compose.container_names_by_service.get(service, [])
+ })
+ if healthy_deps:
+ podman_args.extend([
+ "--label",
+ "io.podman.compose.requires-healthy.v1="
+ + json.dumps(healthy_deps, separators=(",", ":")),
+ ])
sec = norm_as_list(cnt.get("security_opt"))
for sec_item in sec:
podman_args.extend(["--security-opt", sec_item])
--- /dev/null
+++ b/tests/unit/test_healthy_dependency_metadata.py
@@ -0,0 +1,45 @@
+import json
+import unittest
+from unittest import mock
+
+from podman_compose import ServiceDependency, container_to_args
+
+
+class TestHealthyDependencyMetadata(unittest.IsolatedAsyncioTestCase):
+ async def args(self, dependencies, no_deps=False):
+ compose = mock.Mock()
+ compose.dirname = "/tmp"
+ compose.default_net = None
+ compose.networks = {}
+ compose.x_podman = {}
+ compose.container_names_by_service = {
+ "db": ["project_db_2", "project_db_1"],
+ "cache": ["project_cache_1"],
+ }
+ cnt = {
+ "name": "project_app_1", "service_name": "app", "image": "busybox",
+ "depends_on": dependencies,
+ "_deps": {ServiceDependency("db", "service_healthy"),
+ ServiceDependency("cache", "service_started")},
+ }
+ return await container_to_args(compose, cnt, no_deps=no_deps)
+
+ async def test_direct_scaled_health_dependency(self):
+ args = await self.args({"db": {"condition": "service_healthy"}})
+ label = next(a for a in args if a.startswith("io.podman.compose.requires-healthy.v1="))
+ self.assertEqual(json.loads(label.split("=", 1)[1]), ["project_db_1", "project_db_2"])
+ requires = next(a for a in args if a.startswith("--requires="))
+ self.assertEqual(set(requires.split("=", 1)[1].split(",")),
+ {"project_db_1", "project_db_2", "project_cache_1"})
+
+ async def test_transitive_health_not_promoted(self):
+ args = await self.args({"cache": {"condition": "service_started"}})
+ self.assertFalse(any("requires-healthy" in a for a in args))
+
+ async def test_no_deps(self):
+ args = await self.args({"db": {"condition": "service_healthy"}}, no_deps=True)
+ self.assertFalse(any("requires" in a for a in args))
+
+ async def test_started_only(self):
+ args = await self.args({"db": {"condition": "service_started"}})
+ self.assertFalse(any("requires-healthy" in a for a in args))
Thanks for sharing the patch, @harryzz!
The lock-handling pattern and the post-wait state verification (dep.State() == Running) to catch containers that exit immediately after reporting healthy are really solid edge-case catches. I'll make sure to incorporate those guardrails into the native --requires implementation.
Please make sure you follow our LLM policy for all communications https://github.com/podman-container-tools/community/blob/main/LLM_POLICY.md
In general I am not a fan of extending this further for healthchecks. The ordering conditions are already quite complicated, needs proper locking and state sync and actually has to poll/wait for the hc of all containers to be healthy while they could become unhealthy at any time or the containers were already stopped. With requires we just need to start in the right order which is much simpler than having to wait for an unknown amount of time.
Working with healthcheck is much better left to higher level tools such as compose, i.e. I do not think the actual docker cli supports that either.
We also do have the --sdnotify healthy option already which is useful for systemd/quadlet units where one can make the unit active state wait on the hc state with this and then the other systemd dependencies After/Before= can handle it right.
Doing this all again within podman seems unnecessary to me, if you use compose you should stick to compose up/down commands and not use podman start --all to bypass compose after container creation.
Anyhow I leave it open in case another maintainer disagrees with me.
I went back through the start/dependency path, and now I understand your concern better. Adding health waiting to --requires would make it more than dependency ordering, especially around waiting, locking/state synchronization, and what should happen if a dependency becomes unhealthy or stops.
I just want to clarify one point before doing any implementation work: is a later standalone podman start --all intentionally not expected to reproduce a Compose provider's depends_on: condition: service_healthy semantics?
If so, would the expected approach be to keep the workload managed through Compose, or use systemd/Quadlet with the existing health notification mechanism when health-gated reboot/startup ordering is required?
And thank you @Luap99 pointing me to the LLM policy. I've gone through it, and I'll make sure to follow it in my future communication and contributions. Thank you for guiding me and correcting my mistake.
A friendly reminder that this issue had no activity for 30 days.