'Very simple node.js application deployed to k8s cluster, port-forwarding is failing

I have a very simple node.js app, server is listening on port 8282:

const http = require('http');
const os = require('os');
...
...
var server = http.createServer(handler);
server.listen(8282);  

I have a Dockerfile for it:

FROM node:12
COPY app.js /app.js
ENTRYPOINT ["node","app.js"]

Then I built the image myreg/my-app:1.0 successfully & deployed to my k8s cluster (AWS EKS) with the following manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
  namespace: my-ns
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
      - name: my-app
        image: myreg/my-app:1.0
        ports:
        - containerPort: 8282
      imagePullSecrets:
      - name: my-reg-cred

---
apiVersion: v1
kind: Service
metadata:
  name: my-svc
  namespace: my-ns
spec:
  ports:
    - name: http
      port: 8282
      targetPort: 8282
  selector:
    app: my-app

I can see pods are running:

kubectl --namespace=my-ns get po
NAME                      READY   STATUS    RESTARTS   AGE
my-app-5477c9c798-5q4v4   1/1     Running   0          5m3s

Then I want to do port-forwarding, on my terminal:

$kubectl --namespace=my-ns port-forward my-app-5477c9c798-5q4v4  8282
Forwarding from 127.0.0.1:8282 -> 8282
Forwarding from [::1]:8282 -> 8282

I open another terminal window, using curl to communicate with my pod:

curl localhost:8282
curl: (52) Empty reply from server

On the other terminal window where port-forwarding is running:

Handling connection for 8282
E0411 23:12:25.254291   45793 portforward.go:400] an error occurred forwarding 8282 -> 8282: error forwarding port 8282 to pod ca30fad7ea7100d684d1743573dea426caa9a333163ccbca395ed57eaa363061, uid : exit status 1: 2022/04/11 20:12:25 socat[1326] E connect(5, AF=2 127.0.0.1:8282, 16): Connection refused

Why port forwarding is failed in my implementation? What do I miss?



Solution 1:[1]

You app is only listen to localhost, try change server.listen(8282) to server.listen(8282,"0.0.0.0"), rebuild and update your image and restart your deployment.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gohm'c