k8s uses Nodeport to expose services

Posted by mrpickleman on Wed, 24 Jun 2020 04:03:57 +0200

k8s uses Nodeport to expose services

There are many ways to expose K8s services. Here we mainly study how to expose services through Nodeport

First of all, we must understand several concepts before exposing ports:
*< 1 >. Server: it is a cluster instance entry composed of accessing backend pod replicas. It consists of: ` [cluster_ip] ` virtual ip + '[port]' is composed of. '[cluster_ip] ` because there is no physical network object, this virtual ip cannot be ping ed.
*< 2 > '[server]' and '[pod]' replica clusters' are seamlessly connected through the '[label selector]' tag selector.
*< 3 > ` [Kube porxy] 'is similar to a software load balancer, which is responsible for forwarding the server's request load to a backend pod instance.
*Simple summary: user requests arrive at the server cluster entrance through the Node node (IP+port). The server selects the relevant pod cluster according to the label selector, and then loads the request to a certain pod in the back end through the Kube proxy.

Note: the IP and port of the server cluster portal are mapped to the specified port of each node, so the server portal can be accessed by users from any node. Note: for external access, you only need to access from one node, and other nodes are used as standby.

As shown in the figure below:

Next, create a pod instance

#Toggle namespace
kubens showdoc
cat >/home/data/k8s/showdoc_project/showdoc.yaml<<"EOF"
#Create namespace
#apiVersion: v1
#kind: Namespace
#metadata:   
#  name: ns-showdoc
#  labels:     
#    name: ns-showdoc
#
---
apiVersion: v1           #Version number, query: kubectl API version
kind: Service            #Created resources can be pod,server, Deployment, etc
metadata:                #Metadata required
  namespace: ns-showdoc  #Binding namespace
  name: showdoc-svc      #Service resource name
spec:                    #Definition details
  type: NodePort         #type
  selector:              #tag chooser 
    app: container-name-showdoc-pod #The binding reference name is the same as the pod name
  ports:                 #Define port
    - port: 6666         #Port specifies the server port, which is used for internal access of the cluster
      targetPort: 80     #Bind pod port
      nodePort: 31111    #Map the server port to the port of Node node for external network access
      protocol: TCP      #Port protocol
---
#Deployment is responsible for creating and updating apps. After the deployment is created, Kubernetes master will schedule the application instances created by the deployment to each node in the cluster.
#Kubernetes Deployment Controller continuously monitors these instances. If the nodes of the management instance are shut down or deleted, the Deployment Controller will replace them for self-healing

apiVersion: apps/v1        #edition
kind: Deployment           #Specify the created resource role. In the previous version, rc is used. In the new version, rc is replaced by deployment
metadata:                  #metadata
  namespace: ns-showdoc    #Specifies that the namespace defaults to the default space
  name: showdoc-deployment #Define Deployment resource name
spec:                      #Definition details
  replicas: 2              #Define default number of copies
  strategy:                #Since replica is 3, the number of pod s in the whole cluster upgrade process is 1-3 direct
    rollingUpdate:
      maxSurge: 1          #Rolling upgrade starts a pod first
      maxUnavailable: 1    #The maximum number of unavailable pod s allowed for rolling upgrade is 1
  selector:                #Define the tag selector, which should be associated with the app.
    matchLabels:
      app: container-name-showdoc-pod
  template:                #Define the replica template for creating a pod
    metadata:              #Define pod template
      labels:
        namespace: ns-showdoc
        app: container-name-showdoc-pod #Specify the name of the pod
    spec:                  #Template details
      containers:          #Start defining container
      - name: container-name-showdoc-pod #Define container name
        image: star7th/showdoc           #Define image
        imagePullPolicy: IfNotPresent    #IfNotPresent: if there is a local image, use the local image instead of pull. If not, pull. Always: always pull, Never; only use the local image, Never pull
        #command: '[ "/bin/sh","-c","echo 'bestyunyan.com'>/etc/status.log" ]' #Commands executed at startup
        #args:
          #- '-web.external-url=$(EXTERNAL_URL)'
          #- '-alertmanager.url=http://alertmanager:9093/alertmanager'
          #If command and args are not written, the default configuration of Docker is used.
          #If the command is written, but args is not, the default configuration of Docker will be ignored and only the command of the. yaml file (without any parameters) will be executed.
          #If the command is not written but args is written, the command line of ENTRYPOINT configured by default for Docker will be executed, but the calling parameter is args in. yaml.
          #If both command and args are written, the default configuration of Docker is ignored, and. yaml configuration is used.

        #Health examination reference of pod: https://blog.csdn.net/weixin_43466473/article/details/103965984
        #The health check of pod includes many detection methods such as exec, httpGet and TCP. The results of detection include success, failure and unknown failure
        #[https://www.cnblogs.com/cocowool/p/kubernetes_container_probe.html](https://www.cnblogs.com/cocowool/p/kubernetes_container_probe.html)
        #When to use survival probe and when to use ready probe:[ https://www.cnblogs.com/h-gallop/p/11801795.html ] https://www.cnblogs.com/h-gallop/p/11801795.html )
        #livenessProbe:                         #livenessProbe survival probe    
        #  httpGet:                             #There are three detection methods in total: http Get request (more than 200 but less than 400),exec command return value of 0 means OK,tcpsocket monitoring port for detection
        #    path: /install/index.php           #Requested interface path
        #    port: 80                           #get request port
        #    scheme:  HTTP                      #Detection protocol
        #  initialDelaySeconds: 60              #How long is the delay before checking, in seconds
        #  periodSeconds: 5                     #Detect every 5s
        #  timeoutSeconds: 5                    #Timeout of probe, default is 1, unit: Second
        #  successThreshold: 1                  #How many consecutive detections are successful at least
        #  failureThreshold: 5                  #How many consecutive detection failures are considered as failures
        livenessProbe:                         #livenessProbe survival probe
          tcpSocket:                             #There are three detection methods in total: http Get request (more than 200 but less than 400),exec command return value of 0 means OK,tcpsocket monitoring port for detection
            port: 80                           #get request port
          initialDelaySeconds: 60              #How long is the delay before checking, in seconds
          periodSeconds: 5                     #Detect every 5s
          timeoutSeconds: 5                    #Timeout of probe, default is 1, unit: Second
          successThreshold: 1                  #How many consecutive detections are successful at least
          failureThreshold: 5                  #How many consecutive detection failures are considered as failures
        readinessProbe:                        #readnessProbe ready probe to detect if the container is ready
          httpGet:                             #There are three detection methods in total: http Get request (more than 200 but less than 400),exec command return value of 0 means OK,tcpsocket monitoring port for detection
            path: /install/index.php           #Requested interface address
            port: 80                           #get request port
            scheme:  HTTP                      #Detection protocol
          initialDelaySeconds: 60              #How long is the delay before checking, in seconds  
          periodSeconds: 5                     #Detect every 5s
          timeoutSeconds: 5                    #Timeout of probe, default is 1, unit: Second
          successThreshold: 1                  #How many consecutive detections are successful at least
          failureThreshold: 5                  #How many consecutive detection failures are considered as failures
        ports:                                 #Define port
        - name: container-port                 #Define pod name
          containerPort: 80                    #Define pod port
          protocol: TCP                        #Define TCP
        env:                                   #Define environment variables
        - name: ylsys                          #Define key
          value: yunlongshanyingshi            #Define value
        resources:                             #Define restart rules
      restartPolicy: Always                    #With the always restart rule, OnFailure will restart if it fails, and Never will
EOF

reference resources: https://www.cnblogs.com/g2thend/p/11837649.html reference resources: https://blog.csdn.net/weixin_43466473/article/details/103965984

  • Perform creation

[root@master1 showdoc_project]# kubectl create -f showdoc.yaml 
namespace/ns-showdoc created
service/showdoc-svc created
deployment.apps/showdoc-deployment created
NAME                                      READY   STATUS    RESTARTS   AGE
pod/showdoc-deployment-55bf9fd5df-l9xwv   1/1     Running   0          32m
pod/showdoc-deployment-55bf9fd5df-s6lg7   1/1     Running   0          32m

NAME                  TYPE       CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/showdoc-svc   NodePort   179.10.105.126   <none>        6666:31111/TCP   32m

NAME                                 READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/showdoc-deployment   2/2     2            2           32m

NAME                                            DESIRED   CURRENT   READY   AGE
replicaset.apps/showdoc-deployment-55bf9fd5df   2         2         2       32m

From the above results, we can see that:

The vip address of the server is 179.10.105.126, the port of the server vip is 6666, and the port mapped to the node node is 31111 Test on any node

  • ####Access through server:
[root@worker1 ~]#  curl 179.10.105.126:6666/install/index.php -I
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 22 Jun 2020 17:47:36 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.2.7

To access the node directly through the browser:

Topics: Operation & Maintenance Docker PHP less network