Skip to content

Commit

Permalink
Only bind pod ports to host when replicas == 1
Browse files Browse the repository at this point in the history
podman play kube creates a pod per replica and tries to bind all of them to the
same host port. That however can only work when there is one replica as
otherwise multiple pods get bound to the same port on the host.

This fixes containers#16765

Signed-off-by: Dan Čermák <dcermak@suse.com>
  • Loading branch information
dcermak committed Dec 7, 2022
1 parent f672afc commit b19f09b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
11 changes: 8 additions & 3 deletions pkg/specgen/generate/kube/kube.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,12 @@ func ToPodOpt(ctx context.Context, podName string, p entities.PodCreateOptions,
}
p.Net.AddHosts = hosts
}
podPorts := getPodPorts(podYAML.Spec.Containers)

bindToHostPort := true
if podYAML.Replicas != nil && *podYAML.Replicas > 1 {
bindToHostPort = false
}
podPorts := getPodPorts(template.Spec.Containers, bindToHostPort)
p.Net.PublishPorts = podPorts

if dnsConfig := template.Spec.DNSConfig; dnsConfig != nil {
Expand Down Expand Up @@ -937,14 +942,14 @@ func getContainerResources(container v1.Container) (v1.ResourceRequirements, err

// getPodPorts converts a slice of kube container descriptions to an
// array of portmapping
func getPodPorts(containers []v1.Container) []types.PortMapping {
func getPodPorts(containers []v1.Container, bindToHostPort bool) []types.PortMapping {
var infraPorts []types.PortMapping
for _, container := range containers {
for _, p := range container.Ports {
if p.HostPort != 0 && p.ContainerPort == 0 {
p.ContainerPort = p.HostPort
}
if p.HostPort == 0 && p.ContainerPort != 0 {
if p.HostPort == 0 && p.ContainerPort != 0 && bindToHostPort {
p.HostPort = p.ContainerPort
}
if p.Protocol == "" {
Expand Down
28 changes: 28 additions & 0 deletions test/system/700-play.bats
Original file line number Diff line number Diff line change
Expand Up @@ -444,3 +444,31 @@ spec:
run_podman pod rm -a -f
run_podman rm -a -f
}

@test "podman kube play - hostport and replicas" {
HOST_PORT=$(random_free_port)
echo "
apiVersion: v1
kind: Pod
metadata:
labels:
app: test
name: test_pod
spec:
replicas: 3
containers:
- name: server
image: $IMAGE
ports:
- name: hostp
containerPort: $HOST_PORT
" > $PODMAN_TMPDIR/testpod.yaml

run_podman kube play $PODMAN_TMPDIR/testpod.yaml
run_podman pod inspect test_pod --format "{{.InfraConfig.PortBindings}}"
assert "$output" = "map[]"
run_podman kube down $PODMAN_TMPDIR/testpod.yaml

run_podman pod rm -a -f
run_podman rm -a -f
}

0 comments on commit b19f09b

Please sign in to comment.