port.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. "strings"
  18. "github.com/docker/compose/v2/pkg/api"
  19. moby "github.com/docker/docker/api/types"
  20. "github.com/docker/docker/api/types/filters"
  21. )
  22. func (s *composeService) Port(ctx context.Context, projectName string, service string, port uint16, options api.PortOptions) (string, int, error) {
  23. projectName = strings.ToLower(projectName)
  24. list, err := s.apiClient().ContainerList(ctx, moby.ContainerListOptions{
  25. Filters: filters.NewArgs(
  26. projectFilter(projectName),
  27. serviceFilter(service),
  28. containerNumberFilter(options.Index),
  29. ),
  30. })
  31. if err != nil {
  32. return "", 0, err
  33. }
  34. if len(list) == 0 {
  35. return "", 0, fmt.Errorf("no container found for %s%s%d", service, api.Separator, options.Index)
  36. }
  37. container := list[0]
  38. for _, p := range container.Ports {
  39. if p.PrivatePort == port && p.Type == options.Protocol {
  40. return p.IP, int(p.PublicPort), nil
  41. }
  42. }
  43. return "", 0, portNotFoundError(options.Protocol, port, container)
  44. }
  45. func portNotFoundError(protocol string, port uint16, ctr moby.Container) error {
  46. formatPort := func(protocol string, port uint16) string {
  47. return fmt.Sprintf("%d/%s", port, protocol)
  48. }
  49. var containerPorts []string
  50. for _, p := range ctr.Ports {
  51. containerPorts = append(containerPorts, formatPort(p.Type, p.PublicPort))
  52. }
  53. name := strings.TrimPrefix(ctr.Names[0], "/")
  54. return fmt.Errorf("no port %s for container %s: %s", formatPort(protocol, port), name, strings.Join(containerPorts, ", "))
  55. }