部署到 k8s 集群的非常简单的 node.js 应用程序,端口转发失败

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

我有一个非常简单的 node.js 应用程序,服务器正在侦听端口 8282:

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

我有一个Dockerfile

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

然后我成功构建了映像 myreg/my-app:1.0 并使用以下清单部署到我的 k8s 集群 (AWS EKS):

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

我可以看到 pods 是 运行:

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

然后我想在我的终端上做 port-forwarding

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

我打开另一个终端 window,使用 curl 与我的 pod 通信:

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

在另一个终端 window 端口转发是 运行:

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

为什么端口转发在我的实现中失败了?我想念什么?

您的应用只有 listen to localhost,请尝试将 server.listen(8282) 更改为 server.listen(8282,"0.0.0.0"),重建并更新您的映像并重新启动您的部署。