首页 > 解决方案 > Kubernetes NodePort 在外部是不可访问的。拒绝连接

问题描述

嗨,我正在努力学习kubernetes

我正在尝试执行此操作minikube,以下是我所做的:

1.) 编写一个简单的服务器使用Node

2.)Dockerfile为那个特定的Node服务器写一个

3.) 创建一个kubernetes deployment

4.) 创建服务(ClusterIP 类型)

5.) 创建一个服务(NodePort 类型)以公开容器,以便我可以从外部访问(浏览器、curl)

但是当我尝试使用和 `:NodePort的格式连接时<NodePort>:<port>,它给出了一个错误Failed to connect to 192.168.39.192 port 80: Connection denied

这些是我按照上述步骤 (1-5) 创建的文件。

1.) server.js - 这里只有我提到过server.js,relaventpackage.json存在并且当我在本地运行服务器时它们按预期工作(没有在 docker 中部署它),我告诉这个以防你问我的服务器是否正常工作,是的它确实:)

'use strict';

const express = require('express');

// Constants
const PORT = 8080;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
  res.send('Hello world\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

2.) Dockerfile

FROM node:10

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm ci --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

3.) 部署.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: node-web-app
spec:
  replicas: 2
  selector:
    matchLabels:
      name: node-web-app
  template:
    metadata:
      labels:
        # you can specify any labels you want here
        name: node-web-app
    spec:
      containers:
      - name: node-web-app
        # image must be the same as you built before (name:tag)
        image: banuka/node-web-app
        ports:
        - name: http
          containerPort: 8080
          protocol: TCP
        imagePullPolicy: Never
      terminationGracePeriodSeconds: 60

4.) clusterip.yaml

kind: Service
apiVersion: v1
metadata:
  labels:
    # these labels can be anything
    name: node-web-app-clusterip
  name: node-web-app-clusterip
spec:
  selector:
    app: node-web-app
  ports:
    - protocol: TCP
      port: 80
      # target is the port exposed by your containers (in our example 8080)
      targetPort: 8080

5.) 节点端口.yaml

kind: Service
apiVersion: v1
metadata:
  labels:
    name: node-server-nodeport
  name: node-server-nodeport
spec:
  # this will make the service a NodePort service
  type: NodePort
  selector:
    app: node-app-web
  ports:
    - protocol: TCP
      # new -> this will be the port used to reach it from outside
      # if not specified, a random port will be used from a specific range (default: 30000-32767)
      nodePort: 32555
      port: 80
      targetPort: 8080

当我尝试从外面卷曲或使用我的网络浏览器时,它会出现以下错误:

curl: (7) 连接 192.168.39.192 端口 32555 失败:连接被拒绝

ps:pod 和容器也按预期工作。

标签: node.jsdockerkubernetesminikube

解决方案


这有几个可能的原因。第一:您使用的是本地 IP 还是运行 minikube 虚拟机的 IP?验证使用minikube ip。第二:NodePort服务想要使用带有标签app: node-app-web的 pod,但您的 pod 只有标签name: node-web-app 只是为了确保您假设的端口已被使用,请检查minikube service list请求的端口是否已分配。还要检查您的防火墙设置。


推荐阅读