Service(Nodeport)

简介

  1. 这种类型建立在ClusterIP类型之上,其在每个node节点的IP地址的某静态端口(NodePort)暴露服务,因此,它依然会为Service分配集群IP地址,并将此作为NodePort的路由目标。
  2. NodePort类型就是在工作节点的IP地址上选择一个端口用于将集群外部的用户请求转发至目标Service的ClusterIP和Port,因此,这种类型的Service既可如ClusterIP一样受到集群内部客户端Pod的访问,会受到集群外部客户端通过套接字:进行的请求。Service(Nodeport)_第1张图片

 操作实践

创建deployment资源        

# cat myapp-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deploy
  namespace: default
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: nginx 
        ports:
        - containerPort: 80
          name: http

创建NodePort资源

# cat nodeport.yaml 
apiVersion: v1
kind: Service
metadata:
  name: myapp
spec:
  type: NodePort # 指定资源类型为NodePort
  selector:      # 匹配指定标签的资源
    app: myapp
  ports:
  - name: http
    port: 80
    protocol: TCP
    targetPort: 80
    nodePort: 30303   # 指定节点端口,默认30000以上端口随机分配

kubectl apply -f deploment.yaml 

kubectl apply -f nodeport.yaml

查看service信息并验证访问

Service(Nodeport)_第2张图片

  通过master节点的30303端口直接访问到了nginx的pod

[root@k8s-master service]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1                443/TCP        21d
myapp        NodePort    10.100.144.143           80:30303/TCP   24h


[root@k8s-master service]# kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)        AGE
kubernetes   ClusterIP   10.96.0.1                443/TCP        21d
myapp        NodePort    10.100.144.143           80:30303/TCP   24h
[root@k8s-master service]# kubectl describe svc myapp
Name:                     myapp
Namespace:                default
Labels:                   
Annotations:              
Selector:                 app=myapp
Type:                     NodePort
IP:                       10.100.144.143
Port:                     http  80/TCP
TargetPort:               80/TCP
NodePort:                 http  30303/TCP
Endpoints:                10.244.1.21:80,10.244.1.22:80,10.244.2.36:80
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   

你可能感兴趣的:(Kubernetes,kubernetes,docker)