@@ -20,6 +20,7 @@ import (
2020 "context"
2121 "fmt"
2222 "sort"
23+ "strconv"
2324
2425 "github.com/docker/compose/v2/pkg/api"
2526 "github.com/docker/compose/v2/pkg/utils"
@@ -72,7 +73,9 @@ func getDefaultFilters(projectName string, oneOff oneOff, selectedServices ...st
7273
7374func (s * composeService ) getSpecifiedContainer (ctx context.Context , projectName string , oneOff oneOff , stopped bool , serviceName string , containerIndex int ) (moby.Container , error ) {
7475 defaultFilters := getDefaultFilters (projectName , oneOff , serviceName )
75- defaultFilters = append (defaultFilters , containerNumberFilter (containerIndex ))
76+ if containerIndex > 0 {
77+ defaultFilters = append (defaultFilters , containerNumberFilter (containerIndex ))
78+ }
7679 containers , err := s .apiClient ().ContainerList (ctx , moby.ContainerListOptions {
7780 Filters : filters .NewArgs (
7881 defaultFilters ... ,
@@ -83,8 +86,16 @@ func (s *composeService) getSpecifiedContainer(ctx context.Context, projectName
8386 return moby.Container {}, err
8487 }
8588 if len (containers ) < 1 {
86- return moby.Container {}, fmt .Errorf ("service %q is not running container #%d" , serviceName , containerIndex )
89+ if containerIndex > 0 {
90+ return moby.Container {}, fmt .Errorf ("service %q is not running container #%d" , serviceName , containerIndex )
91+ }
92+ return moby.Container {}, fmt .Errorf ("service %q is not running" , serviceName )
8793 }
94+ sort .Slice (containers , func (i , j int ) bool {
95+ x , _ := strconv .Atoi (containers [i ].Labels [api .ContainerNumberLabel ])
96+ y , _ := strconv .Atoi (containers [j ].Labels [api .ContainerNumberLabel ])
97+ return x < y
98+ })
8899 container := containers [0 ]
89100 return container , nil
90101}
0 commit comments