Skip to content

Commit 11277d4

Browse files
authored
Merge pull request kubernetes#89401 from liggitt/fix_kubectl_explicit_local_port_for_service
Fix kubectl explicit local port for service
2 parents 07a7c49 + dfeb617 commit 11277d4

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

Lines changed: 6 additions & 3 deletions
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

Lines changed: 29 additions & 0 deletions
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)