port.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. )
  21. func (s *composeService) Port(ctx context.Context, projectName string, service string, port uint16, options api.PortOptions) (string, int, error) {
  22. projectName = strings.ToLower(projectName)
  23. container, err := s.getSpecifiedContainer(ctx, projectName, oneOffInclude, false, service, options.Index)
  24. if err != nil {
  25. return "", 0, err
  26. }
  27. for _, p := range container.Ports {
  28. if p.PrivatePort == port && p.Type == options.Protocol {
  29. return p.IP, int(p.PublicPort), nil
  30. }
  31. }
  32. return "", 0, portNotFoundError(options.Protocol, port, container)
  33. }
  34. func portNotFoundError(protocol string, port uint16, ctr moby.Container) error {
  35. formatPort := func(protocol string, port uint16) string {
  36. return fmt.Sprintf("%d/%s", port, protocol)
  37. }
  38. var containerPorts []string
  39. for _, p := range ctr.Ports {
  40. containerPorts = append(containerPorts, formatPort(p.Type, p.PublicPort))
  41. }
  42. name := strings.TrimPrefix(ctr.Names[0], "/")
  43. return fmt.Errorf("no port %s for container %s: %s", formatPort(protocol, port), name, strings.Join(containerPorts, ", "))
  44. }