feat(up): stream the logs while --wait waits for the services

Without --detach, `up --wait` now attaches to the containers and streams
their logs until the services are running|healthy, then ends the
session and leaves them up. Until now --wait silently forced --detach,
so a service failing to become healthy left no clue about why.

--detach --wait keeps the previous silent behavior, and --dry-run
stays on the detached plan. The library Validate accepts Wait with
Attach, and still rejects OnExit, ExitCodeFrom and Watch with it. The
navigation menu is disabled while waiting.

Signed-off-by: Guillaume Lours <glours@users.noreply.github.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Guillaume Lours 2026-11-04 14:06:13 +01:00 • committed by Guillaume Lours
parent 0e0005664c
commit d79cb959b5
16 changed files with 200 additions and 57 deletions

View file

@ -171,7 +171,7 @@ func upCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *Backend
flags.StringArrayVar(&up.attach, "attach", []string{}, "Restrict attaching to the specified services. Incompatible with --attach-dependencies.")
flags.StringArrayVar(&up.noAttach, "no-attach", []string{}, "Do not attach (stream logs) to the specified services")
flags.BoolVar(&up.attachDependencies, "attach-dependencies", false, "Automatically attach to log output of dependent services")
flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.")
flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy, streaming their logs unless --detach is set")
flags.IntVar(&up.waitTimeout, "wait-timeout", 0, "Maximum duration in seconds to wait for the project to be running|healthy")
flags.BoolVarP(&up.watch, "watch", "w", false, "Watch source code and rebuild/refresh containers when files are updated.")
flags.BoolVar(&up.navigationMenu, "menu", false, "Enable interactive shortcuts when running attached. Incompatible with --detach. Can also be enable/disable by setting COMPOSE_MENU environment var.")
@ -190,16 +190,10 @@ func validateFlags(up *upOptions, create *createOptions) error {
if up.cascadeStop && up.cascadeFail {
return errors.New("--abort-on-container-failure cannot be combined with --abort-on-container-exit")
}
if up.wait {
if up.attachDependencies || up.cascadeStop || len(up.attach) > 0 {
return errors.New("--wait cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
}
up.Detach = true
}
if create.Build && create.noBuild {
return errors.New("--build and --no-build are incompatible")
}
if up.Detach && (up.attachDependencies || up.cascadeStop || up.cascadeFail || len(up.attach) > 0 || up.watch) {
if (up.Detach || up.wait) && (up.attachDependencies || up.cascadeStop || up.cascadeFail || len(up.attach) > 0 || up.watch) {
if up.wait {
return errors.New("--wait cannot be combined with --abort-on-container-exit, --abort-on-container-failure, --attach, --attach-dependencies or --watch")
} else {

View file

@ -216,3 +216,30 @@ func TestWarnIgnoredJobs(t *testing.T) {
assert.Assert(t, strings.Contains(msg, "migrate"), msg)
assert.Assert(t, !strings.Contains(msg, "backup"), msg)
}
// --wait alone keeps the session attached to stream the logs until the services
// are running|healthy; only an explicit --detach silences it.
func TestValidateFlagsWait(t *testing.T) {
tests := []struct {
name string
up upOptions
wantErr string
}{
{name: "wait alone stays attached", up: upOptions{wait: true}},
{name: "wait with watch", up: upOptions{wait: true, watch: true}, wantErr: "--wait cannot be combined with"},
{name: "wait with abort on container failure", up: upOptions{wait: true, cascadeFail: true}, wantErr: "--wait cannot be combined with"},
{name: "wait with abort on container exit", up: upOptions{wait: true, cascadeStop: true}, wantErr: "--wait cannot be combined with"},
{name: "wait with attach", up: upOptions{wait: true, attach: []string{"web"}}, wantErr: "--wait cannot be combined with"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateFlags(&tt.up, &createOptions{})
if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
return
}
assert.NilError(t, err)
assert.Assert(t, !tt.up.Detach, "--wait must not imply --detach")
})
}
}

View file

@ -64,7 +64,7 @@ hook runs again. Running `compose down` also removes them.
| `--scale` | `stringArray` | | Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present. |
| `-t`, `--timeout` | `int` | `0` | Use this timeout in seconds for container shutdown when attached or when containers are already running |
| `--timestamps` | `bool` | | Show timestamps |
| `--wait` | `bool` | | Wait for services to be running\|healthy. Implies detached mode. |
| `--wait` | `bool` | | Wait for services to be running\|healthy, streaming their logs unless --detach is set |
| `--wait-timeout` | `int` | `0` | Maximum duration in seconds to wait for the project to be running\|healthy |
| `-w`, `--watch` | `bool` | | Watch source code and rebuild/refresh containers when files are updated. |
| `-y`, `--yes` | `bool` | | Assume "yes" as answer to all prompts and run non-interactively |

View file

@ -302,7 +302,8 @@ options:
- option: wait
value_type: bool
default_value: "false"
description: Wait for services to be running|healthy. Implies detached mode.
description: |
Wait for services to be running|healthy, streaming their logs unless --detach is set
deprecated: false
hidden: false
experimental: false

View file

@ -33,6 +33,45 @@ func TestUpWait(t *testing.T) {
ServiceState("oneshot", "exited"))
}
// https://github.com/docker/compose/issues/9122: up --wait ran fully detached,
// leaving CI with no way to see why a service was slow or never got healthy.
func TestUpWaitStreamsLogs(t *testing.T) {
NewScenario(t, "up --wait must stream the services' logs while waiting, then return leaving them running").
Step("up --wait relays the service output and returns once it is healthy",
ComposeCmd("up", "--wait").Within(60*time.Second),
StdoutContains("booting"),
StdoutContains("ready-to-serve"),
ServiceHealthy("app"),
ServiceState("app", "running"))
}
// Pins that the --wait readiness check runs on the caller's context: on the
// session's own it fails with "context canceled" once the followed service exits.
func TestUpWaitNoAttachOneShot(t *testing.T) {
NewScenario(t, "up --wait must still succeed when the only service whose logs are followed exits during the wait").
Step("up --wait returns once the long-running service is up, the followed one-shot having exited",
ComposeCmd("up", "--wait", "--no-attach", "longrunning").Within(60*time.Second),
ServiceState("longrunning", "running"),
ServiceState("oneshot", "exited"))
}
func TestUpWaitDetachedStaysQuiet(t *testing.T) {
NewScenario(t, "up --detach --wait must not stream the services' logs, as an explicit --detach asks for").
Step("up -d --wait returns once the service is healthy without relaying its output",
ComposeCmd("up", "-d", "--wait").Within(60*time.Second),
OutputNotContains("ready-to-serve"),
ServiceHealthy("app"))
}
func TestUpWaitStreamsLogsOnUnhealthy(t *testing.T) {
NewScenario(t, "up --wait must stream the logs of a service that never gets healthy, and still fail").
Step("up --wait fails with the service output in the log",
ComposeCmd("up", "--wait").MayFail().Within(60*time.Second),
ExitCode(1),
StdoutContains("failing-to-boot"),
ServiceState("app", "running"))
}
func TestUpWaitTimeout(t *testing.T) {
s := NewScenario(t, "up --wait --wait-timeout must fail once the timeout expires instead of silently succeeding")
s.Step("up --wait fails after the timeout with the service still starting",

View file

@ -0,0 +1,9 @@
services:
app:
image: alpine
init: true
command: sh -c 'echo booting; sleep 3; echo ready-to-serve; touch /tmp/ready; sleep infinity'
healthcheck:
test: ["CMD", "test", "-f", "/tmp/ready"]
interval: 1s
retries: 30

View file

@ -0,0 +1,11 @@
services:
oneshot:
image: alpine
command: echo 'hello world'
longrunning:
image: alpine
init: true
depends_on:
oneshot:
condition: service_completed_successfully
command: sleep infinity

View file

@ -0,0 +1,9 @@
services:
app:
image: alpine
init: true
command: sh -c 'echo booting; sleep 3; echo ready-to-serve; touch /tmp/ready; sleep infinity'
healthcheck:
test: ["CMD", "test", "-f", "/tmp/ready"]
interval: 1s
retries: 30

View file

@ -0,0 +1,9 @@
services:
app:
image: alpine
init: true
command: sh -c 'echo failing-to-boot; sleep infinity'
healthcheck:
test: ["CMD", "false"]
interval: 1s
retries: 3

View file

@ -390,8 +390,10 @@ type StartOptions struct {
// by Up's foreground session only; ignored by Start.
ExitCodeFrom string
// Wait won't return until containers reached the running|healthy state.
// Up honors it in detached mode only (Attach nil): combined with Attach it
// is rejected, see UpOptions.Validate.
// Up honors it in detached mode (Attach nil), and combined with Attach it
// streams the logs until that state is reached, then returns leaving the
// containers running. The session options OnExit, ExitCodeFrom and Watch
// are rejected with it, see UpOptions.Validate.
Wait bool
WaitTimeout time.Duration
// Services names the services the user explicitly targeted; it only
@ -402,7 +404,7 @@ type StartOptions struct {
// Start.
Watch bool
// NavigationMenu enables the keyboard menu of Up's foreground session;
// ignored by Start.
// ignored by Start, and by Up when Wait is set.
NavigationMenu bool
}

View file

@ -63,8 +63,8 @@ func incompatible(reason string, options ...string) error {
//
// Up has two modes, selected by Start.Attach: detached (nil) returns once the
// containers are started, interactive (set) keeps running a foreground session.
// Validate only checks the combinations listed below: Wait with Attach, and
// OnExit, ExitCodeFrom or Watch without Attach. Other mode-specific fields
// Validate only checks the combinations listed below: OnExit, ExitCodeFrom or
// Watch without Attach, or with Wait. Other mode-specific fields
// (e.g. Services, AttachTo, NavigationMenu) are not checked and may be ignored
// in the mode they do not apply to.
//
@ -82,7 +82,6 @@ func (o UpOptions) Validate() error {
if err := o.Create.Validate(); err != nil {
errs = append(errs, err)
}
errs = append(errs, validateWaitIsDetached(o.Start)...)
errs = append(errs, validateDetachedHasNoSession(o.Start)...)
switch len(errs) {
case 0:
@ -94,35 +93,25 @@ func (o UpOptions) Validate() error {
}
}
// validateWaitIsDetached: Wait blocks until the services are running|healthy
// and then returns, which only happens in detached mode. In an interactive
// session that check would be silently dropped.
// CLI: --wait implies --detach and is incompatible with --attach and
// --attach-dependencies.
func validateWaitIsDetached(s StartOptions) []error {
if s.Wait && s.Attach != nil {
return []error{incompatible("Wait returns once services are running or healthy, which is detached mode, while Attach starts an interactive session",
"Start.Wait", "Start.Attach")}
}
return nil
}
// validateDetachedHasNoSession: the cascade policy, the exit code selection
// and watch are all features of the interactive session, they have no effect
// when Attach is nil. Every such option set is reported. When Wait is set, it
// is the reason why the session cannot be started, so it is part of the conflict.
// CLI: --detach is incompatible with --abort-on-container-exit,
// when Attach is nil, and when Wait is set the session ends as soon as the
// services are running or healthy. Every such option set is reported. When
// Wait is set, it is part of the conflict.
// CLI: --detach and --wait are incompatible with --abort-on-container-exit,
// --abort-on-container-failure, --exit-code-from (which implies
// --abort-on-container-exit) and --watch.
func validateDetachedHasNoSession(s StartOptions) []error {
if s.Attach != nil {
if s.Attach != nil && !s.Wait {
return nil
}
reason := "Attach is nil (detached mode), so no interactive session runs to honor "
options := []string{"Start.Attach"}
reason := "no interactive session outlives the start (Attach is nil, or Wait ends it once the services are running or healthy) to honor "
var options []string
if s.Wait {
reason = "Wait implies detached mode and Attach is nil, so no interactive session runs to honor "
options = []string{"Start.Wait", "Start.Attach"}
options = append(options, "Start.Wait")
}
if s.Attach == nil {
options = append(options, "Start.Attach")
}
conflict := func(field string) error {
return incompatible(reason+field, append(slices.Clone(options), "Start."+field)...)

View file

@ -55,9 +55,10 @@ func TestUpOptionsValidate(t *testing.T) {
{name: "interactive watch", start: StartOptions{Attach: attached, Watch: true}},
{name: "interactive everything", start: StartOptions{Attach: attached, AttachTo: []string{"web"}, OnExit: CascadeFail, ExitCodeFrom: "web", Watch: true, NavigationMenu: true}},
// wait is detached
{name: "wait with attach", start: StartOptions{Wait: true, Attach: attached}, conflict: []string{"Start.Wait", "Start.Attach"}},
{name: "wait with attach and timeout", start: StartOptions{Wait: true, WaitTimeout: time.Second, Attach: attached}, conflict: []string{"Start.Wait", "Start.Attach"}},
// wait streams the logs until the services are running|healthy
{name: "wait with attach", start: StartOptions{Wait: true, Attach: attached}},
{name: "wait with attach cascade stop", start: StartOptions{Wait: true, Attach: attached, OnExit: CascadeStop}, conflict: []string{"Start.Wait", "Start.OnExit"}},
{name: "wait with attach watch", start: StartOptions{Wait: true, Attach: attached, Watch: true}, conflict: []string{"Start.Wait", "Start.Watch"}},
// session-only options require a session
{name: "detached cascade stop", start: StartOptions{OnExit: CascadeStop}, conflict: []string{"Start.Attach", "Start.OnExit"}},
@ -160,10 +161,10 @@ func TestUpOptionsValidateReportsAllConflicts(t *testing.T) {
want: [][]string{{"Start.Attach", "Start.Watch"}},
},
{
// the session options are fine once Attach is set, only Wait conflicts
// Attach is set, but Wait ends the session before the options could apply
name: "wait with attach and session options",
start: StartOptions{Wait: true, Attach: attached, OnExit: CascadeStop, ExitCodeFrom: "web", Watch: true},
want: [][]string{{"Start.Wait", "Start.Attach"}},
want: [][]string{{"Start.Wait", "Start.OnExit"}, {"Start.Wait", "Start.ExitCodeFrom"}, {"Start.Wait", "Start.Watch"}},
},
}
for _, tt := range tests {

View file

@ -49,9 +49,11 @@ func (s *composeService) Up(ctx context.Context, project *types.Project, options
if err := options.Validate(); err != nil {
return err
}
// A dry run has no session to stream logs from: --wait stays the detached plan.
detached := options.Start.Attach == nil || (options.Start.Wait && s.dryRun)
var created *createdUp
err := Run(ctx, tracing.SpanWrapFunc("project/up", tracing.ProjectOptions(ctx, project), func(ctx context.Context) error {
if options.Start.Attach == nil {
if detached {
return s.upDetached(ctx, project, options)
}
var err error
@ -62,7 +64,7 @@ func (s *composeService) Up(ctx context.Context, project *types.Project, options
return err
}
if options.Start.Attach == nil {
if detached {
return err
}
if s.dryRun {
@ -151,14 +153,20 @@ func (s *composeService) upDetached(ctx context.Context, project *types.Project,
if !options.Start.Wait {
return nil
}
return s.awaitProjectReady(ctx, project, options.Start.WaitTimeout)
}
// awaitProjectReady blocks until every service of the project is running or
// healthy, within timeout when it is set: the --wait verification, once the
// plan ran.
func (s *composeService) awaitProjectReady(ctx context.Context, project *types.Project, timeout time.Duration) error {
// The plan may have created or recreated containers: this verification
// needs their current IDs, which the pre-execution observed snapshot
// above doesn't have for a container that didn't exist yet at
// observation time. The listing runs on the caller's context, before the
// --wait-timeout window opens, so daemon-listing latency never eats into
// the budget the readiness polling is owed (any deadline it hits is the
// caller's own, unrelated to --wait-timeout, and is returned as such).
// doesn't have for a container that didn't exist yet at observation time.
// The listing runs on the caller's context, before the --wait-timeout
// window opens, so daemon-listing latency never eats into the budget the
// readiness polling is owed (any deadline it hits is the caller's own,
// unrelated to --wait-timeout, and is returned as such).
containers, err := s.getContainers(ctx, project.Name, oneOffExclude, true)
if err != nil {
return err
@ -176,8 +184,8 @@ func (s *composeService) upDetached(ctx context.Context, project *types.Project,
// context's Err() report DeadlineExceeded too, inherited from the
// parent, even though this window's own timer never fired.
origCtx := ctx
if options.Start.WaitTimeout > 0 {
withTimeout, cancel := context.WithTimeout(ctx, options.Start.WaitTimeout)
if timeout > 0 {
withTimeout, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ctx = withTimeout
}
@ -190,8 +198,8 @@ func (s *composeService) upDetached(ctx context.Context, project *types.Project,
}
}
if err := s.waitDependencies(ctx, project, project.Name, depends, containers); err != nil {
if options.Start.WaitTimeout > 0 && origCtx.Err() == nil && errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Errorf("application not healthy after %s", options.Start.WaitTimeout)
if timeout > 0 && origCtx.Err() == nil && errors.Is(ctx.Err(), context.DeadlineExceeded) {
return fmt.Errorf("application not healthy after %s", timeout)
}
return err
}
@ -379,6 +387,14 @@ func (s *composeService) runInteractiveUp(ctx context.Context, created *createdU
// We use the parent context without cancellation as we manage sigterm to stop the stack
err = created.run.runStart(context.WithoutCancel(ctx), u.printer.HandleEvent)
err = translateWaitTimeout(err)
if err == nil && options.Start.Wait {
// --wait streams the logs only until the services are running|healthy,
// then ends the session leaving them up. The caller's ctx, not
// globalCtx: the monitor cancels the latter once every container is
// gone, which must not abort the verification of one-shot services.
err = s.awaitProjectReady(ctx, project, options.Start.WaitTimeout)
cancel()
}
if err != nil && !u.isTerminated.Load() { // Ignore error if the process is terminated
cancel()
_ = u.eg.Wait()
@ -398,10 +414,14 @@ func (s *composeService) runInteractiveUp(ctx context.Context, created *createdU
}
// setupNavigationMenu initializes the interactive keyboard menu when enabled.
// It returns a nil menu when the menu is disabled, when no menu implementation
// It returns a nil menu when the menu is disabled (or Wait is set), when no menu implementation
// was configured (WithNavigationMenu), or when the keyboard can't be grabbed —
// then disabling the option.
func (s *composeService) setupNavigationMenu(ctx context.Context, options *api.UpOptions, signalChan chan os.Signal) (NavigationMenu, error) {
if options.Start.Wait {
// the session ends on its own once the services are up: no menu to drive
options.Start.NavigationMenu = false
}
if !options.Start.NavigationMenu {
return nil, nil
}

View file

@ -36,9 +36,9 @@ func TestUpRejectsIncompatibleOptionsBeforeAnySideEffect(t *testing.T) {
want []string
}{
{
name: "wait with attach",
options: api.UpOptions{Start: api.StartOptions{Wait: true, Attach: &testLogConsumer{}}},
want: []string{"Start.Wait", "Start.Attach"},
name: "wait with attach and cascade",
options: api.UpOptions{Start: api.StartOptions{Wait: true, Attach: &testLogConsumer{}, OnExit: api.CascadeStop}},
want: []string{"Start.Wait", "Start.OnExit"},
},
{
name: "detached with cascade",

View file

@ -517,6 +517,25 @@ func TestUpInteractiveDryRunOnlyCreates(t *testing.T) {
assert.Assert(t, strings.Contains(h.out.String(), "interactive run is not supported in dry-run mode"), "output: %q", h.out.String())
}
// TestUpInteractiveDryRunWaitStaysDetached: --wait in a dry run keeps the
// detached plan: there is no session to stream logs from, and no interactive
// run to announce as unsupported. The harness container has already exited, so
// the readiness verdict itself (an error here) is not what this pins.
func TestUpInteractiveDryRunWaitStaysDetached(t *testing.T) {
h := newInteractiveUpHarness(t)
h.svc.dryRun = true
options := interactiveUpOptions()
options.Start.Wait = true
_ = h.svc.Up(t.Context(), interactiveUpProject(), options)
for _, call := range []string{"attach", "events"} {
assert.Equal(t, h.daemon.indexOf(call), -1, "%s must not be reached by a detached --wait: %v", call, h.daemon.recorded())
}
assert.Assert(t, h.daemon.indexOf("start") >= 0, "the detached plan ran: %v", h.daemon.recorded())
assert.Assert(t, !strings.Contains(h.out.String(), "interactive run is not supported in dry-run mode"), "output: %q", h.out.String())
}
// TestUpInteractiveStartPhaseSurvivesCancellation: the Start phase runs on a
// context that outlives the caller's, since an interruption is the session's to
// handle once it is set up (it stops what the application started). Canceled

View file

@ -336,3 +336,16 @@ func TestWithNavigationMenu(t *testing.T) {
assert.NilError(t, WithNavigationMenu(func(bool, bool, chan<- os.Signal) NavigationMenu { return nil })(s))
assert.Assert(t, s.navigationMenu != nil)
}
func TestSetupNavigationMenuDisabledByWait(t *testing.T) {
fm := &fakeMenu{}
svc, _ := newTestService(t, WithNavigationMenu(func(bool, bool, chan<- os.Signal) NavigationMenu { return fm }))
options := api.UpOptions{Start: api.StartOptions{NavigationMenu: true, Wait: true}}
menu, err := svc.setupNavigationMenu(t.Context(), &options, make(chan os.Signal, 1))
assert.NilError(t, err)
assert.Assert(t, menu == nil)
assert.Assert(t, !fm.opened, "a session ending once the services are up must not grab the keyboard")
assert.Assert(t, !options.Start.NavigationMenu)
}