Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion pkg/compose/convergence.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,14 @@ func (s *composeService) waitDependencies(ctx context.Context, project *types.Pr
case ServiceConditionRunningOrHealthy:
isHealthy, err := s.isServiceHealthy(ctx, waitingFor, true)
if err != nil {
// A container that exited with code 0 can be treated as
// successfully completed (init/oneshot containers) when the
// service won't be restarted by Docker after a clean exit.
var exitErr *containerExitError
if errors.As(err, &exitErr) && exitErr.exitCode == 0 && !restartsOnExit0(project, dep) {
s.events.On(containerEvents(waitingFor, exited)...)
return nil
Comment on lines +490 to +491
Copy link

Copilot AI Mar 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the exit-code-0 success path, this treats the whole dependency as satisfied and emits "exited" events for all containers in waitingFor. If the dependency service is scaled >1 and only one replica exits(0) while others are still starting/unhealthy, waitDependencies would return success prematurely. Consider limiting this shortcut to single-container services, or re-checking every container in waitingFor and only succeeding when they have all cleanly exited(0) (and emitting events only for the containers that actually exited).

Suggested change
s.events.On(containerEvents(waitingFor, exited)...)
return nil
// Only treat this as a satisfied dependency when exactly one
// container is being waited on. For multi-container (scaled)
// services, we must not mark all containers as exited or
// consider the dependency satisfied based on a single replica.
if len(waitingFor) == 1 {
s.events.On(containerEvents(waitingFor, exited)...)
return nil
}
// For multiple containers, fall through to the standard
// required/optional handling below.

Copilot uses AI. Check for mistakes.
}
Comment on lines +485 to +492
Copy link

Copilot AI Mar 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new "exit code 0 treated as success" behavior in the ServiceConditionRunningOrHealthy wait path isn’t covered by tests. There’s currently only minimal coverage for waitDependencies (scale=0 and service_started); adding a unit test that simulates ContainerInspect returning Status=exited/ExitCode=0 and asserts waitDependencies returns nil (and does not fail the overall wait) would help prevent regressions.

Copilot uses AI. Check for mistakes.
if !config.Required {
s.events.On(containerReasonEvents(waitingFor, skippedEvent,
fmt.Sprintf("optional dependency %q is not running or is unhealthy", dep))...)
Expand Down Expand Up @@ -552,6 +560,29 @@ func (s *composeService) waitDependencies(ctx context.Context, project *types.Pr
return err
}

// restartsOnExit0 reports whether Docker will restart the named service after
// it exits with code 0. Only restart policies "always" and "unless-stopped"
// cause a restart on clean exit; "no", "on-failure", and unset do not.
// For deploy.restart_policy.condition, "any" (and the non-spec but accepted
// "always" and "unless-stopped") cause a restart on clean exit.
func restartsOnExit0(project *types.Project, serviceName string) bool {
service, err := project.GetService(serviceName)
if err != nil {
return false
}
switch service.Restart {
case types.RestartPolicyAlways, types.RestartPolicyUnlessStopped:
return true
}
if service.Deploy != nil && service.Deploy.RestartPolicy != nil {
switch service.Deploy.RestartPolicy.Condition {
case "any", "always", "unless-stopped":
return true
Comment on lines +573 to +580
Copy link

Copilot AI Mar 24, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

restartsOnExit0 compares service.Restart directly to types.RestartPolicyAlways/UnlessStopped, but restart strings can legally include a suffix (e.g. "on-failure:3") and this codebase already parses restart policies via strings.Cut + mapRestartPolicyCondition (see getRestartPolicy in pkg/compose/create.go). As written, values like "always:1" or "any" would be misclassified, which can cause --wait to treat an exit(0) as success even though the service would be restarted. Consider parsing service.Restart the same way as getRestartPolicy and basing the decision on the mapped engine mode (Always/UnlessStopped).

Copilot uses AI. Check for mistakes.
}
}
return false
}

func shouldWaitForDependency(serviceName string, dependencyConfig types.ServiceDependency, project *types.Project) (bool, error) {
if dependencyConfig.Condition == types.ServiceConditionStarted {
// already managed by InDependencyOrder
Expand Down Expand Up @@ -803,6 +834,18 @@ func (s *composeService) getLinks(ctx context.Context, projectName string, servi
return links, nil
}

// containerExitError is returned by isServiceHealthy when a container has exited.
// It carries the exit code so callers can distinguish clean exits (code 0)
// from failures without parsing error strings.
type containerExitError struct {
name string
exitCode int
}

func (e *containerExitError) Error() string {
return fmt.Sprintf("container %s exited (%d)", e.name, e.exitCode)
}

func (s *composeService) isServiceHealthy(ctx context.Context, containers Containers, fallbackRunning bool) (bool, error) {
for _, c := range containers {
res, err := s.apiClient().ContainerInspect(ctx, c.ID, client.ContainerInspectOptions{})
Expand All @@ -813,7 +856,7 @@ func (s *composeService) isServiceHealthy(ctx context.Context, containers Contai
name := ctr.Name[1:]

if ctr.State.Status == container.StateExited {
return false, fmt.Errorf("container %s exited (%d)", name, ctr.State.ExitCode)
return false, &containerExitError{name: name, exitCode: ctr.State.ExitCode}
}

noHealthcheck := ctr.Config.Healthcheck == nil || (len(ctr.Config.Healthcheck.Test) > 0 && ctr.Config.Healthcheck.Test[0] == "NONE")
Expand Down
29 changes: 29 additions & 0 deletions pkg/compose/convergence_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package compose

import (
"context"
"errors"
"fmt"
"net/netip"
"strings"
Expand Down Expand Up @@ -366,6 +367,34 @@ func TestIsServiceHealthy(t *testing.T) {

_, err := tested.(*composeService).isServiceHealthy(ctx, containers, true)
assert.ErrorContains(t, err, "exited")
var exitErr *containerExitError
assert.Assert(t, errors.As(err, &exitErr))
assert.Equal(t, exitErr.exitCode, 1)
})

t.Run("exited container with exit code 0 returns containerExitError", func(t *testing.T) {
containerID := "test-container-id"
containers := Containers{
{ID: containerID},
}

apiClient.EXPECT().ContainerInspect(ctx, containerID, gomock.Any()).Return(client.ContainerInspectResult{
Container: container.InspectResponse{
ID: containerID,
Name: "test-container",
State: &container.State{
Status: "exited",
ExitCode: 0,
},
Config: &container.Config{},
},
}, nil)

_, err := tested.(*composeService).isServiceHealthy(ctx, containers, true)
assert.Assert(t, err != nil, "expected error for exited container")
var exitErr *containerExitError
assert.Assert(t, errors.As(err, &exitErr))
assert.Equal(t, exitErr.exitCode, 0)
})

t.Run("healthy container with healthcheck", func(t *testing.T) {
Expand Down
109 changes: 109 additions & 0 deletions pkg/compose/start_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/*
Copyright 2020 Docker Compose CLI authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package compose

import (
"testing"

"github.com/compose-spec/compose-go/v2/types"
"gotest.tools/v3/assert"
)

func TestRestartsOnExit0(t *testing.T) {
tests := []struct {
name string
service types.ServiceConfig
expected bool
}{
{
name: "no restart policy",
service: types.ServiceConfig{Name: "init"},
expected: false,
},
{
name: "restart no",
service: types.ServiceConfig{Name: "init", Restart: types.RestartPolicyNo},
expected: false,
},
{
name: "restart on-failure",
service: types.ServiceConfig{Name: "init", Restart: types.RestartPolicyOnFailure},
expected: false,
},
{
name: "restart always",
service: types.ServiceConfig{Name: "web", Restart: types.RestartPolicyAlways},
expected: true,
},
{
name: "restart unless-stopped",
service: types.ServiceConfig{Name: "web", Restart: types.RestartPolicyUnlessStopped},
expected: true,
},
{
name: "deploy restart policy condition any",
service: types.ServiceConfig{
Name: "web",
Deploy: &types.DeployConfig{
RestartPolicy: &types.RestartPolicy{Condition: "any"},
},
},
expected: true,
},
{
name: "deploy restart policy condition on-failure",
service: types.ServiceConfig{
Name: "web",
Deploy: &types.DeployConfig{
RestartPolicy: &types.RestartPolicy{Condition: "on-failure"},
},
},
expected: false,
},
{
name: "deploy restart policy condition none",
service: types.ServiceConfig{
Name: "web",
Deploy: &types.DeployConfig{
RestartPolicy: &types.RestartPolicy{Condition: "none"},
},
},
expected: false,
},
{
name: "deploy restart policy condition unless-stopped",
service: types.ServiceConfig{
Name: "web",
Deploy: &types.DeployConfig{
RestartPolicy: &types.RestartPolicy{Condition: "unless-stopped"},
},
},
expected: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
project := &types.Project{
Services: types.Services{
tt.service.Name: tt.service,
},
}
assert.Equal(t, restartsOnExit0(project, tt.service.Name), tt.expected)
})
}
}
Loading