Skip to content

Commit ef2eaa4

Browse files
author
Marius Ziemke
committed
fix kubectl port-forward for services with explicit local port
1 parent 672aa55 commit ef2eaa4

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,7 +185,10 @@ func translateServicePortToTargetPort(ports []string, svc corev1.Service, pod co
185185
return nil, err
186186
}
187187

188-
if int32(portnum) != containerPort || localPort == "" {
188+
// should fail when localPort is empty (=> use random local port)
189+
localportnum, err := strconv.Atoi(localPort)
190+
191+
if int32(portnum) != containerPort || localPort == "" || (int32(localportnum) != containerPort && err == nil) {
189192
translated = append(translated, fmt.Sprintf("%s:%d", localPort, containerPort))
190193
} else {
191194
translated = append(translated, fmt.Sprintf("%d", containerPort))

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)