SpringBoot e-commerce project mall (40K + STAR) address: github.com/macrozheng/…

Abstract

If you watch Kubernetes is so hot! Doesn’t it smell good to spend 10 minutes playing it? Basically, you can play K8S. In fact, there are some advanced features in K8S that are also worth learning, such as elastic scaling applications, rolling updates, configuration management, storage volumes, gateway routing, and so on. Today we’ll take a look at some of these advanced features and hopefully help you out!

The core concept

Let’s start by looking at some of the core concepts that will help you use the advanced features of the K8S.

ReplicaSet

ReplicaSet ensures that a specified number of Pod copies are running at any given time. Usually used to ensure the availability of a given number of identical pods. It is recommended to use Deployment to manage ReplicaSet rather than using ReplicaSet directly.

ConfigMap

ConfigMap is an API object used to store unconfidential data in key-value pairs. When used, Pod can be used as an environment variable, a command-line parameter, or a configuration file in a storage volume. Use ConfigMap to separate your configuration data from your application code.

Volume

Volume refers to the storage Volume that contains the data directory accessible by the container in Pod. The files in the container are temporarily stored on disk, can be lost when the container crashes, and cannot be shared among multiple PODS. Using storage volumes can solve both problems.

Common storage volumes are as follows:

  • ConfigMap: The configMap volume provides a way to inject configuration data into a Pod. Data stored in ConfigMap objects can be referenced by volumes of type ConfigMap and then used by containerized applications running in PODS.
  • EmptyDir: The emptyDir volume can be used to store cached data. When a Pod is dispatched to a Node, the emptyDir volume is created and remains as long as the Pod is running on that Node. Data in the emptyDir volume is permanently deleted when Pod is removed from the node.
  • HostPath: The hostPath volume can mount files or directories from the host node’s file system to your Pod. The host in Minikube refers to the virtual machine where the Minikube resides.
  • Local: A local volume represents a mounted local storage device, such as a disk, partition, or directory. A local volume can only be used as a statically created persistent volume and does not support dynamic configuration.
  • NFS: NFS volumes mount NFS (network file system) to your Pod.
  • PersistentVolumeClaim: The persistentVolumeClaim volume is used to mount a PersistentVolume into a Pod. A persistent volume (PV) is a block of Storage in a cluster. It can be supplied by an administrator in advance or dynamically by using a Storage Class. A persistent volume is a cluster resource similar to a node.

Ingress

Ingress is similar to the gateway service in K8S. It is an API object that manages external access to services in a cluster, typically through HTTP. Ingress can provide load balancing, SSL termination, and name-based virtual hosting.

Advanced features

Enlarge shrinks application

As traffic increases, we need to expand the application to meet user demand. When traffic is reduced, the application needs to be scaled to reduce server overhead. Scaling in K8S is achieved by changing the number of copies in Deployment.

  • Obtain all Deployment using the following command:
kubectl get deployments
Copy the code
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
kubernetes-nginx   1/1     1            1           43h
Copy the code
  • To obtain all ReplicaSet replicas, run the following command:
kubectl get rs
Copy the code
NAME                          DESIRED   CURRENT   READY   AGE
kubernetes-nginx-78bcc44665   1         1         1       43h
Copy the code
  • Expand the application to four instances and view all:
kubectl scale deployments/kubernetes-nginx --replicas=4
Copy the code
[macro@linux-local root]$ kubectl get deployments
NAME               READY   UP-TO-DATE   AVAILABLE   AGE
kubernetes-nginx   4/4     4            4           43h
Copy the code
  • If you look at all the PODS, there are already four running on different IP addresses.
kubectl get pods -o wide
Copy the code
NAME                                READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running   2          43h   172.17.0.3   minikube   <none>           <none>
kubernetes-nginx-78bcc44665-dvq4t   1/1     Running   0          84s   172.17.0.8   minikube   <none>           <none>
kubernetes-nginx-78bcc44665-thzg9   1/1     Running   0          84s   172.17.0.7   minikube   <none>           <none>
kubernetes-nginx-78bcc44665-w7xqd   1/1     Running   0          84s   172.17.0.6   minikube   <none>           <none>
Copy the code
  • Scale the application to 2 instances;
kubectl scale deployments/kubernetes-nginx --replicas=2
Copy the code
NAME                                READY   STATUS    RESTARTS   AGE   IP           NODE       NOMINATED NODE   READINESS GATES
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running   2          44h   172.17.0.3   minikube   <none>           <none>
kubernetes-nginx-78bcc44665-w7xqd   1/1     Running   0          11m   172.17.0.6   minikube   <none>           <none>
Copy the code

Scroll to update

Rolling updates allow a Pod instance to be progressively updated with a new instance, with no downtime for Deployment updates. K8S can not only implement rolling updates, but also support rollback operations.

  • There are currently four Nginx running1.10Examples of versions:
[macro@linux-local root]$ kubectl get pods
NAME                                READY   STATUS    RESTARTS   AGE
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running   2          44h
kubernetes-nginx-78bcc44665-jpw2g   1/1     Running   0          5s
kubernetes-nginx-78bcc44665-w7xqd   1/1     Running   0          59m
kubernetes-nginx-78bcc44665-xx8s5   1/1     Running   0          5s
Copy the code
  • Can be achieved bykubectl describeCommand to view the version number of the mirror:
[macro @ Linux - local root] $kubectl the describe the pods | grep Image Image: nginx: 1.10 the Image ID: docker-pullable://nginx@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575Copy the code
  • throughkubectl set imageCommand to update the version number of the Nginx image to1.19At this point, K8S will perform rolling update and gradually stop1.10Version and start1.19Version instance;
Container name = container image: image version number
kubectl setImage deployments/kubernetes - nginx nginx = nginx: 1.19Copy the code
Stop 1 old instance and create 2 new instances
NAME                                READY   STATUS              RESTARTS   AGE
kubernetes-nginx-66f67cd758-rbcz5   0/1     ContainerCreating   0          11s
kubernetes-nginx-66f67cd758-s9ck8   0/1     ContainerCreating   0          11s
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running             2          45h
kubernetes-nginx-78bcc44665-jpw2g   0/1     Terminating         0          15m
kubernetes-nginx-78bcc44665-w7xqd   1/1     Running             0          75m
kubernetes-nginx-78bcc44665-xx8s5   1/1     Running             0          15m
1 instance has been stopped and 2 new instances are still being created
NAME                                READY   STATUS              RESTARTS   AGE
kubernetes-nginx-66f67cd758-rbcz5   0/1     ContainerCreating   0          30s
kubernetes-nginx-66f67cd758-s9ck8   0/1     ContainerCreating   0          30s
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running             2          45h
kubernetes-nginx-78bcc44665-w7xqd   1/1     Running             0          75m
kubernetes-nginx-78bcc44665-xx8s5   1/1     Running             0          15m
All four new instances have been createdNAME READY STATUS RESTARTS AGE kubernetes-nginx-66f67cd758-jn926 1/1 Running 0 48s kubernetes-nginx-66f67cd758-rbcz5 1/1  Running 0 3m12s kubernetes-nginx-66f67cd758-s9ck8 1/1 Running 0 3m12s kubernetes-nginx-66f67cd758-smr7n 1/1 Running 0 44sCopy the code
  • Use at this pointkubectl describeCommand to view the image version number, found that Nginx has been updated to1.19Version:
[macro @ Linux - local root] $kubectl the describe the pods | grep Image Image: nginx: 1.19 the Image ID: docker-pullable://nginx@sha256:4cf620a5c81390ee209398ecc18e5fb9dd0f5155cd82adcbae532fec94006fb9Copy the code
  • If you want to roll back to the original version, just usekubectl rollout undoCommand.
kubectl rollout undo deployments/kubernetes-nginx
Copy the code

Configuration management

ConfigMap allows you to separate configuration files from image files to make containerized applications portable. Let’s show how to inject ConfigMap properties into Pod environment variables.

  • Adding a Configuration Filenginx-config.yamlThe ConfigMap command is used to create a ConfigMapnginx-config, the configuration information is storeddataUnder the node:
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
  namespace: default
data:
  nginx-env: test
Copy the code
  • applicationnginx-config.yamlFile create ConfigMap:
kubectl create -f nginx-config.yaml
Copy the code
  • Get all configMaps:
kubectl get configmap
Copy the code
NAME               DATA   AGE
kube-root-ca.crt   1      2d22h
nginx-config       1      13s
Copy the code
  • throughyamlFormat View the contents of ConfigMap:
kubectl get configmaps nginx-config -o yaml
Copy the code
apiVersion: v1
data:
  nginx-env: test
kind: ConfigMap
metadata:
  creationTimestamp: "2021-01-08T01:49:44Z"
  managedFields:
  - apiVersion: v1
    fieldsType: FieldsV1
    fieldsV1:
      f:data:
        . : {}
        f:nginx-env: {}
    manager: kubectl-create
    operation: Update
    time: "2021-01-08T01:49:44Z"
  name: nginx-config
  namespace: default
  resourceVersion: "61322"
  uid: a477567f-2aff-4a04-9a49-f19220baf0d3
Copy the code
  • Adding a Configuration Filenginx-deployment.yamlTo create Deployment, deploy an Nginx service that references the properties in ConfigMap in the Nginx environment variable:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: Nginx: 1.10
          ports:
            - containerPort: 80
          env:
            - name: NGINX_ENV Set environment variables in Nginx
              valueFrom:
                configMapKeyRef:
                  name: nginx-config Set the name of ConfigMap
                  key: nginx-env # The key to be evaluated
Copy the code
  • Apply configuration file file to create Deployment:
kubectl apply -f nginx-deployment.yaml
Copy the code
  • Check the environment variables in Pod after the creation is successfulNGINX_ENVThe variable has been injected;
kubectl exec deployments/nginx-deployment -- env
Copy the code
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=nginx-deployment-66fcf997c-xxdsb
NGINX_ENV=test
Copy the code

Storage Volume Usage

With the volume, we can mount external data to the container for the application in the container to access, so that even if the container crashes, the data can survive.

  • Remember that when we used Docker to deploy Nginx, we used Nginx’sHTML, logs, confThe directory is mounted externally into the container;
docker run -p 80:80 --name nginx \
-v /mydata/nginx/html:/usr/share/nginx/html \
-v /mydata/nginx/logs:/var/log/ nginx \ - v/mydata/nginx/conf: / etc/nginx \ - d nginx: 1.10Copy the code
  • Minikube can be thought of as a virtual machine, we can use MinikubesshCommand to access it;
minikube ssh
Copy the code
  • Minikube has one by defaultdockerThe user, let’s reset its password;
sudo passwd docker
Copy the code
  • Created in MinikubemydataDirectory;
midir /home/docker/mydata
Copy the code
  • We need to copy the Nginx data directory to Minikube, in order to achieve the directory mount, note that docker users can only modify/home/dockerThe files in the directory we passscpCommand to copy files;
SCP - r/home/macro/mydata/nginx [email protected]: / home/docker/mydata/nginxCopy the code
  • Adding a Configuration Filenginx-volume-deployment.yamlFor creating Deployment:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-volume-deployment
  labels:
    app: nginx
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: nginx
          image: Nginx: 1.10
          ports:
            - containerPort: 80
          volumeMounts:
            - mountPath: /usr/share/nginx/html
              name: html-volume
            - mountPath: /var/log/nginx
              name: logs-volume
            - mountPath: /etc/nginx
              name: conf-volume
      volumes:
        - name: html-volume
          hostPath:
            path: /home/docker/mydata/nginx/html
            type: Directory
        - name: logs-volume
          hostPath:
            path: /home/docker/mydata/nginx/logs
            type: Directory
        - name: conf-volume
          hostPath:
            path: /home/docker/mydata/nginx/conf
            type: Directory
Copy the code
  • Apply the configuration file to create Deployment;
kubectl apply -f nginx-volume-deployment.yaml
Copy the code
  • Adding a Configuration Filenginx-service.yamlTo create a Service;
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
    - name: http
      protocol: TCP
      port: 80
      targetPort: 80
      nodePort: 30080
Copy the code
  • Create a Service using a configuration file.
kubectl apply -f nginx-service.yaml
Copy the code
  • Service Service access port.
[macro@linux-local nginx]$ kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 6d23h kubernetes-nginx NodePort 10.106.227.54 < None > 80:30158/TCP 5d22h nginx-service NodePort 10.103.72.111 < none > 80:30080 / TCP 7 sCopy the code
  • You can run the CURL command to access the Nginx home page.
curl $(minikube ip):30080
Copy the code

The gateway routing

Ingress can be used as the gateway of K8S to provide service routing and load balancing.

  • Minikube does not have Ingress plug-in enabled by default.
minikube addons enable ingress
Copy the code
  • The Ingress image cannot be downloaded from Minikube. The Ingress image cannot be downloaded from Minikube.
[macro@linux-local ~]$ minikube addons enable ingress
* Verifying ingress addon...
Copy the code
  • To resolve this problem, manually download the third-party image, mark it as the required image, and re-enable the Ingress plug-in.
Find the Pod that started the problem
kubectl get pods -n kube-system
# Check the cause of the startup failure
kubectl describe ingress-nginx-controller-xxx -n kube-system
# Connect to Minikube
minikube ssh
# the image that needs to be downloaded is not available.Docker pull us. GCR. IO/k8s - artifacts - prod/ingress - nginx/controller: v0.40.2# Download the third-party alternative image (go to DockerHub website to search)Docker pull pollyduan/ingress - nginx - controller: v0.40.2# Change the image nameDocker tag pollyduan/ingress - nginx - controller: v0.40.2 us. GCR. IO/k8s - artifacts - prod/ingress - nginx/controller: v0.40.2Copy the code
  • Restart the plugin and check whether the Ingress is running.
kubectl get pods -n kube-system
Copy the code
NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-admission-create-krpgk        0/1     Completed   0          46h
ingress-nginx-admission-patch-wnxlk         0/1     Completed   3          46h
ingress-nginx-controller-558664778f-wwgws   1/1     Running     2          46h
Copy the code
  • Adding a Configuration Filenginx-ingress.yamlUsed to create the Ingress;
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: / $1
spec:
  rules:
    - host: nginx-volume.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: nginx-service
                port:
                  number: 80
Copy the code
  • Apply configuration file to create Ingress;
kubectl apply -f nginx-ingress.yaml
Copy the code
  • View all the Ingress, at this point we are ready to passnginx-volume.comTo access the Nginx service running in Pod;
kubectl get ingress
Copy the code
NAME CLASS HOSTS ADDRESS PORTS AGE nginx-ingress < None > nginx-volume.comCopy the code
  • Need to modifyhostFile, notice to switch torootAccount modification:
Switch to user root
su -
Change the host file
vi /etc/hosts
Add the following record
192.168.49.2 nginx-volume.com
Copy the code
  • You can run the CURL command to query the Nginx home page.
curl nginx-volume.com
Copy the code

conclusion

It’s really convenient to extend and manage containerized applications through K8S. With a few commands, we can achieve zero downtime updates, and if something goes wrong, we can roll back with one command. But a lot of command-line operations can be tedious, and it would be nice to have a visual tool to manage K8S directly.

The resources

The official document: kubernetes. IO/useful/docs/hom…

In this paper, making github.com/macrozheng/… Already included, welcome everyone Star!