Kubernetes NodePort不监听

时间:2020-07-27 21:51:32

标签: nginx kubernetes k3s

我正在使用k3d(在docker中为k3s)做一些教程,而我的yml看起来像这样:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
          ports:
          - containerPort: 80

---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
  - name: http
    port: 80
    targetPort: 80

结果节点端口为31747:

:~$ kubectl get service
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.43.0.1       <none>        443/TCP        18m
nginx        NodePort    10.43.254.138   <none>        80:31747/TCP   17m

:~$ kubectl get endpoints
NAME         ENDPOINTS         AGE
kubernetes   172.18.0.2:6443   22m
nginx        10.42.0.8:80      21m

但是wget不起作用:

:~$ wget localhost:31747
Connecting to localhost:31747 ([::1]:31747)
wget: can't connect to remote host: Connection refused
:~$

我错过了什么?我确保我的标签都说app: nginx,而我的containerPortporttargetPort都是80

2 个答案:

答案 0 :(得分:2)

问题是,NodePort范围是从主机映射到充当节点的Docker容器的。命令docker ps将向您显示,有关更多详细信息,您可以docker inspect $container_id并查看Ports下的NetworkSettings属性。我周围没有k3d,但这是一个实物示例。

$ docker ps
CONTAINER ID        IMAGE                         COMMAND                  CREATED             STATUS              PORTS                       NAMES
1d2225b83a73        kindest/node:v1.17.0          "/usr/local/bin/entr…"   18 hours ago        Up 18 hours         127.0.0.1:32769->6443/tcp   kind-control-plane
$ docker inspect kind-control-plane
[
    {
        # [...]
        "NetworkSettings": {
            # [...]
            "Ports": {
                "6443/tcp": [
                    {
                        "HostIp": "127.0.0.1",
                        "HostPort": "32769"
                    }
                ]
            },
        # [...]
    }
]

如果不是,按照注释中的建议使用kubectl port-forward可能是最简单的方法。或者,开始研究Ingress。首选Ingress是暴露集群外部工作负载的方法,对于Ingress,则为they have support。看来k3d也有办法map the ingress port to the host

答案 1 :(得分:0)

也许,您的 pod 正在另一个工作节点上运行,而不是 localhost。你应该使用正确的节点ip。