slimtoolkit/slim · error
cannot detect host port
Error message
cannot detect host port
What it means
After starting `kubectl port-forward`, this code scans its stdout for the actual locally-bound host port. If the process is running but no line matching the expected output pattern was parsed, it returns this error while still handing back the running command.
Source
Thrown at pkg/app/master/kubernetes/kubectl.go:176
if err != nil {
return cmd, "", err
}
if err := cmd.Start(); err != nil {
return cmd, "", err
}
var actualHostPort int
pattern := fmt.Sprintf("Forwarding from %s:%s -> %s", address, "%d", podPort)
scanner := bufio.NewScanner(out)
for scanner.Scan() {
n, err := fmt.Sscanf(scanner.Text(), pattern, &actualHostPort)
if err == nil && n == 1 {
return cmd, fmt.Sprintf("%d", actualHostPort), nil
}
}
return cmd, "", errors.New("cannot detect host port")
}
View on GitHub (pinned to 81940d17fa)
Solutions
- Check kubectl stdout/stderr for connection errors (bad pod, port closed)
- Verify the kubectl version's port-forward output format matches what is parsed
- Increase the wait timeout and confirm the pod/port are valid before forwarding
Example fix
// ensure the forwarded port is valid before calling
if _, err := strconv.Atoi(podPort); err != nil { return fmt.Errorf("bad podPort %q", podPort) } Defensive patterns
Strategy: try-catch
Validate before calling
// sanity-check the target before forwarding
_, err := clientset.CoreV1().Pods(ns).Get(ctx, pod, metav1.GetOptions{})
if err != nil { return err } // pod must exist and be running Try / catch
cmd, hostPort, err := k.PortForward(ctx, pod, addr, "", podPort)
if err != nil && strings.Contains(err.Error(), "cannot detect host port") {
// capture cmd stdout/stderr, kill cmd, retry once with verbose kubectl
} Prevention
- Pin a kubectl version whose port-forward output format you've tested
- Confirm pod is Running and the container port exists before forwarding
- Always terminate the returned cmd on this error to avoid orphans
When it happens
Trigger: kubectl emits output not matching the expected "Forwarding from ... -> ..." pattern (locale/CLI version differences, warnings interleaved, stderr vs stdout) so Sscanf never yields n==1.
Common situations: Newer kubectl versions changing the message format; kubectl writing forwarding info to stderr; immediate connection failures producing error text instead of the forwarding line.
Related errors
- malformed Kubernetes workload name
- podPort cannot be empty
- Pod terminated
- Pod not running
- Container terminated
AI-assisted analysis of slimtoolkit/slim@81940d17fa (2026-08-31).
Data as JSON: /api/errors/a9d4da556bee5f0f.
Report an issue: GitHub.