Skip to content

Commit 4d552d8

Browse files
authored
Merge pull request kubernetes#89402 from liggitt/automated-cherry-pick-of-#89401-upstream-release-1.18
Automated cherry pick of kubernetes#89401: fix kubectl port-forward for services with explicit local
2 parents 99dada0 + dd342d7 commit 4d552d8

File tree

2 files changed

+35
-3
lines changed

2 files changed

+35
-3
lines changed

staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward.go

+6-3
Original file line numberDiff line numberDiff line change
@@ -185,10 +185,13 @@ func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod co
185185
return nil, err
186186
}
187187

188-
if int32(portnum) != containerPort || localPort == "" {
189-
translated = append(translated, fmt.Sprintf("%s:%d", localPort, containerPort))
188+
// convert the resolved target port back to a string
189+
remotePort = strconv.Itoa(int(containerPort))
190+
191+
if localPort != remotePort {
192+
translated = append(translated, fmt.Sprintf("%s:%s", localPort, remotePort))
190193
} else {
191-
translated = append(translated, fmt.Sprintf("%d", containerPort))
194+
translated = append(translated, remotePort)
192195
}
193196
}
194197
return translated, nil

staging/src/k8s.io/kubectl/pkg/cmd/portforward/portforward_test.go

+29
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,35 @@ func TestTranslateServicePortToTargetPort(t *testing.T) {
209209
translated: []string{":8080"},
210210
err: false,
211211
},
212+
{
213+
name: "test success 1 (int port with explicit local port)",
214+
svc: corev1.Service{
215+
Spec: corev1.ServiceSpec{
216+
Ports: []corev1.ServicePort{
217+
{
218+
Port: 8080,
219+
TargetPort: intstr.FromInt(8080),
220+
},
221+
},
222+
},
223+
},
224+
pod: corev1.Pod{
225+
Spec: corev1.PodSpec{
226+
Containers: []corev1.Container{
227+
{
228+
Ports: []corev1.ContainerPort{
229+
{
230+
Name: "http",
231+
ContainerPort: int32(8080)},
232+
},
233+
},
234+
},
235+
},
236+
},
237+
ports: []string{"8000:8080"},
238+
translated: []string{"8000:8080"},
239+
err: false,
240+
},
212241
{
213242
name: "test success 2 (clusterIP: None)",
214243
svc: corev1.Service{

0 commit comments

Comments
 (0)