【原文链接】
一、NodePort类型的Service简介
ClusterIP类型和Headless类型的Service都只能在集群环境内部访问,如果想开放给集群环境以外访问,那就需要使用NodePort类型,NodePort的工作原理其实就是将service的端口映射到Node的端口上,然后通过NodeIP:NodePort 来访问Service
二、环境准备
编写deployment.yaml文件,内容如下:
apiVersion: v1
kind: Namespace
metadata:
name: dev
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: pc-deployment
namespace: dev
spec:
replicas: 3
selector:
matchLabels:
app: nginx-pod
template:
metadata:
labels:
app: nginx-pod
spec:
containers:
- name: nginx
image: nginx:1.17.1
ports:
- containerPort: 80
然后使用如下命令创建资源
[root@master service]# kubectl apply -f deployment.yaml
namespace/dev created
deployment.apps/pc-deployment created
[root@master service]#
查看创建的资源如下:
[root@master service]# kubectl get deploy,pod -n dev -o wide
NAME READY UP-TO-DATE AVAILABLE AGE CONTAINERS IMAGES SELECTOR
deployment.apps/pc-deployment 3/3 3 3 17m nginx nginx:1.17.1 app=nginx-pod
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
pod/pc-deployment-5ffc5bf56c-mqwst 1/1 Running 0 17m 10.244.2.191 node2 <none> <none>
pod/pc-deployment-5ffc5bf56c-qbznm 1/1 Running 0 17m 10.244.1.53 node1 <none> <none>
pod/pc-deployment-5ffc5bf56c-zxnsx 1/1 Running 0 17m 10.244.2.190 node2 <none> <none>
[root@master service]#
三、创建NodePort类型Service
编辑nodeport.yaml文件,内容如下:
apiVersion: v1
kind: Service
metadata:
name: service-nodeport
namespace: dev
spec:
selector:
app: nginx-pod
type: NodePort
ports:
- port: 80
nodePort: 30002
targetPort: 80
使用如下命令创建服务
[root@master service]# kubectl apply -f nodeport.yaml
service/service-nodeport created
[root@master service]#
查看所创建的资源如下:
[root@master service]# kubectl get service,deployment,pod -n dev
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
service/service-nodeport NodePort 10.107.215.143 <none> 80:30002/TCP 10m
NAME READY UP-TO-DATE AVAILABLE AGE
deployment.apps/pc-deployment 3/3 3 3 23h
NAME READY STATUS RESTARTS AGE
pod/pc-deployment-5ffc5bf56c-mqwst 1/1 Running 0 23h
pod/pc-deployment-5ffc5bf56c-qbznm 1/1 Running 0 23h
pod/pc-deployment-5ffc5bf56c-zxnsx 1/1 Running 0 23h
[root@master service]#
此时可以在集群环境之外,通过节点ip:port访问服务,如这里节点ip为192.168.16.40,端口为30002,如下: