port.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package compose
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/docker/compose/v2/pkg/api"
  18. moby "github.com/docker/docker/api/types"
  19. "github.com/docker/docker/api/types/filters"
  20. )
  21. func (s *composeService) Port(ctx context.Context, project string, service string, port int, options api.PortOptions) (string, int, error) {
  22. list, err := s.apiClient.ContainerList(ctx, moby.ContainerListOptions{
  23. Filters: filters.NewArgs(
  24. projectFilter(project),
  25. serviceFilter(service),
  26. containerNumberFilter(options.Index),
  27. ),
  28. })
  29. if err != nil {
  30. return "", 0, err
  31. }
  32. if len(list) == 0 {
  33. return "", 0, fmt.Errorf("no container found for %s_%d", service, options.Index)
  34. }
  35. container := list[0]
  36. for _, p := range container.Ports {
  37. if p.PrivatePort == uint16(port) && p.Type == options.Protocol {
  38. return p.IP, int(p.PublicPort), nil
  39. }
  40. }
  41. return "", 0, err
  42. }