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