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

Abstract

My Mall e-commerce actual combat project has been using Docker container deployment, many friends suggested a Kubernetes deployment. Recently just learn Kubernetes, ready to update a wave! Today we first to learn the core concept of Kubernetes and basic use, I hope to help you!

Introduction of Kubernetes

Kubernetes (abbreviated as K8S with eight letters between K and S) is an open source system for automatically deploying, extending, and managing containerized applications. It groups the containers that make up the application into logical units for easy administration and service discovery. Kubernetes is a product of Google’s 15 years of experience in operating and maintaining production environments, as well as the best ideas and practices of the community.

Kubernetes has the following features:

  • Service discovery and load balancing: You can use unfamiliar service discovery mechanisms without modifying your application.
  • Storage orchestration: Automatically mounts the selected storage system, including local storage.
  • Secret and configuration management: Deploying updated Secrets and application configurations does not require rebuilding container images or exposing Secret information in software stack configurations.
  • Batch execution: In addition to services, Kubernetes can manage your batch and CI workloads, replacing failed containers when desired.
  • Horizontal scaling: Automatically scaling applications with a simple command, a UI, or based on CPU usage.
  • Automated online and rollback: Kubernetes brings changes to the application or its configuration online in a step-by-step manner, while monitoring application health to ensure that you don’t terminate all instances at the same time.
  • Automatic boxing: Automatically places containers according to resource requirements and other constraints without compromising availability.
  • Self-repair: Restart containers that fail, replace and reschedule containers when nodes die, and kill containers that do not respond to user-defined health checks.

Minikube profile

Minikube is a lightweight Kubernetes implementation that creates a VM on a local computer and deploys a simple cluster containing only one node. Minikube is available for Linux, MacOS, and Windows systems. The Minikube CLI provides a variety of operations to boot the cluster into work, including start, stop, view status, and delete.

Kubernetes core concepts

Since there are many core concepts in Kubernetes, learning them is very helpful to understand the use of Kubernetes, so let’s study these core concepts first.

Node

Kubernetes cluster refers to Kubernetes coordinating a cluster of highly available computers, each of which works with each other as an independent unit.

A Kubernetes cluster contains two types of resources:

  • Master: Manages the entire cluster. Coordinate all activities in the cluster, such as scheduling applications, maintaining the required states of applications, expanding applications, and rolling out new updates.
  • Node: Used to host running applications. It can be a virtual machine or a physical machine that acts as a worker machine in a Kubernetes cluster. Each Node has Kubelet, which manages nodes and acts as a proxy for Node communication with the Master. Node also has tools for handling container operations such as Docker or RKT.

Deployment

Deployment is responsible for creating and updating instances of the application. Once Deployment is created, Kubernetes Master schedules the application instances to the various nodes in the cluster. If the node hosting the instance is shut down or deleted, the Deployment controller replaces the instance with an instance on another node in the cluster. This provides a self-healing mechanism to solve machine failure maintenance problems.

You can create and manage Deployment using the Kubernetes command line interface Kubectl. Kubectl uses the Kubernetes API to interact with clusters.

Pod

Pod is a logical host that hosts application instances. Includes one or more application containers (such as Docker) and some shared resources (shared storage, network, operational information, and so on) for those containers.

Service

A Service is an abstraction layer that defines a logical set of pods and supports external traffic exposure, load balancing, and Service discovery for these Pods.

Although each Pod has a unique IP address, these IP addresses are not exposed outside the cluster without a Service. Service allows your application to receive traffic. A Service can also be exposed using the ServiceSpec flag type, which is as follows:

  • ClusterIP (default) : Exposes the Service on the internal IP of the cluster. This type makes the Service accessible only from within the cluster.
  • NodePort: Exposes the Service on the same port on each selected Node in the cluster using NAT. use<NodeIP>:<NodePort>Access the Service from outside the cluster. Is a superset of ClusterIP.
  • LoadBalancer: create an external LoadBalancer (if supported) in the current cloud and assign a fixed external IP to the Service. Is a superset of NodePorts.
  • ExternalName: Expose the Service with any name (specified by ExternalName in the spec) by returning a CNAME record with that name. No proxy is used.

Docker installation

Because Kubernetes relies on the container runtime (the software that runs the container), the more common container runtimes are Docker, Containerd, and Cri-O. Here select Docker, first install the Docker environment on the Linux server.

  • The installationyum-utils:
yum install -y yum-utils device-mapper-persistent-data lvm2
Copy the code
  • Add docker repository location to yum source:
yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
Copy the code
  • Install the Docker:
yum install docker-ce
Copy the code
  • Start the Docker:
systemctl start docker
Copy the code

Minikube installation

  • First we need to download the binary installation package of Minikube and install:
curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64
sudo install minikube-linux-amd64 /usr/local/bin/minikube
Copy the code
  • Then use the following command to start Minikube:
minikube start
Copy the code
  • If you’re usingrootThe user cannot start Minikube with the following message, because Minikube does not allow root permission to start, you need to create a non-root account.
* minikube v1.16.0 on Centos 7.6.1810
* Automatically selected the docker driver
* The "docker" driver should not be used with root privileges.
* If you are running minikube within a VM, consider using --driver=none:
*   https://minikube.sigs.k8s.io/docs/reference/drivers/none/

X Exiting due to DRV_AS_ROOT: The "docker" driver should not be used with root privileges.
Copy the code
  • This creates a property that belongs todockerUser groupsmacroUser and switch to the user;
# create user
useradd -u 1024 -g docker macro
Set user password
passwd macro
# Switch user
su macro
Copy the code
  • Again usingminikube startRun the Minikube command to start the Minikube. After the command is successfully started, the following information is displayed:
* To pull new external images, you may need to configure a proxy: https://minikube.sigs.k8s.io/docs/reference/networking/proxy/ * Preparing Kubernetes v1.20.0 on Docker 20.10.0... - Generating certificates and keys ... - Booting up control plane ... - Configuring RBAC rules ... * Verifying Kubernetes components... * Enabled addons: default-storageclass, storage-provisioner * kubectl not found. If you need it, try:'minikube kubectl -- get pods -A'
* Done! kubectl is now configured to use "minikube" cluster and "default" namespace by default
Copy the code

The use of Kubernetes

Create the cluster

Minikube allows you to create a single-node K8S cluster on which both the cluster manager Master and the nodes responsible for running the application are deployed.

  • Check the version number of Minikube:
minikube version
Copy the code
Minikube version: v1.16.0 commit: 9 f1e482427589ff8451c4723b6ba53bb9742fbb1Copy the code
  • Kubectl install kubectl for the first time
minikube kubectl version
Copy the code
Client Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:59:43Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"20", GitVersion:"v1.20.0", GitCommit:"af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38", GitTreeState:"clean", BuildDate:"2020-12-08T17:51:19Z", GoVersion:"go1.15.5", Compiler:"gc", Platform:"linux/amd64"}
Copy the code
  • If you want to use the kubectl command directly, you can copy it to/binDown to the table:
Find kubectl command location
find / -name kubectl
Copy it to /binCp/mydata docker/volumes/minikube / _data while forming/lib/minikube binaries/v1.20.0 / kubectl/bin /Use kubectl directly
kubectl version
Copy the code
  • To view cluster details:
kubectl cluster-info
Copy the code
Kubernetes control plane is running at https://192.168.49.2:8443
KubeDNS is running at https://192.168.49.2:8443/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
Copy the code
  • Looking at all the nodes in the cluster, you can see that Minikube creates a simple single-node cluster:
kubectl get nodes
Copy the code
NAME STATUS ROLES AGE VERSION minikube Ready Control-plane, Master 46m V1.20.0Copy the code

The deployment of application

Once the K8S cluster is running, containerized applications can be deployed on it. By creating a Deployment object, K8S can be instructed how to create and update instances of the application.

  • Specify the application image and create a Deployment. Here create an Nginx application:
Kubectl create deployment kubernetes-nginx --image=nginx:1.10Copy the code
  • K8S generates the following actions when creating a Deployment:

    • Select an appropriate Node to deploy the application.
    • Deploy the application on Node;
    • Redeploy an application if it is abnormally shut down or deleted.
  • View all Deployment:

kubectl get deployments
Copy the code
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
kubernetes-nginx      1/1     1            1           21h
Copy the code
  • We can get throughkubectl proxyCommand to create a proxy that accesses the K8S API directly through the exposed interface. Here the interface to query the K8S version is called;
[macro@linux-local root]$kubectl proxy Starting to serve on 127.0.0.1:8001 [root@linux-local ~]# curl http://localhost:8001/version
{
  "major": "1"."minor": "20"."gitVersion": "v1.20.0"."gitCommit": "af46c47ce925f4c4ad5cc8d1fca46c7b77d13b38"."gitTreeState": "clean"."buildDate": "2020-12-08T17:51:19Z"."goVersion": "go1.15.5"."compiler": "gc"."platform": "linux/amd64"
}
Copy the code

Check the application

You can view container logs and execute container internal commands by performing operations on the Pod running the application.

  • Check the status of all pods in K8s:
kubectl get pods
Copy the code
NAME                                   READY   STATUS             RESTARTS   AGE
kubernetes-nginx-78bcc44665-8fnnn      1/1     Running            1          21h
Copy the code
  • View Pod details, including IP addresses, occupied ports, and mirroring usage.
kubectl describe pods
Copy the code
Name: kubernetes-nginx-78bCC44665-8fnnn Namespace: default Priority: 0 Node: minikube/192.168.49.2 Start Time: Tue, 05 Jan 2021 13:57:46 +0800 Labels: app=kubernetes-nginx pod-template-hash=78bcc44665 version=v1 Annotations: < None > Status: Running IP: 172.17.0.7 IPs: IP: 172.17.0.7 Controlled By: ReplicaSet/kubernetes-nginx-78bcc44665 Containers: nginx: Container ID: 31 eb1277e507ec4cf8a27b66a9f4f30fb919d17f4cd914c09eb4cfe8322504b2 docker: / / Image: nginx: 1.10 the Image ID: docker-pullable://nginx@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575 Port: <none> Host Port: <none> State: Running Started: Wed, 06 Jan 2021 09:22:40 +0800 Last State: Terminated Reason: Completed Exit Code: 0 Started: Tue, 05 Jan 2021 14:24:55 +0800 Finished: Tue, 05 Jan 2021 17:32:48 +0800 Ready: True Restart Count: 1 Environment: <none> Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-dhr4b (ro) Conditions: Type Status Initialized True Ready True ContainersReady True PodScheduled True Volumes: default-token-dhr4b: Type: Secret (a volume populated by a Secret) SecretName: default-token-dhr4b Optional:false
QoS Class:       BestEffort
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:          <none>
Copy the code
  • Set the name of the Pod to an environment variable for later use$POD_NAMETo apply the Pod name:
export POD_NAME=kubernetes-nginx-78bcc44665-8fnnn
Copy the code
  • To view the logs printed by Pod:
kubectl logs $POD_NAME
Copy the code
  • useexecYou can execute commands in the Pod container, as used hereenvCommand to view environment variables:
kubectl exec $POD_NAME -- env
Copy the code
PATH=/usr/local/sbin:/usr/local/ bin: / usr/sbin, / usr/bin, / sbin, / bin HOSTNAME = kubernetes - bcc44665 nginx - 78-8 FNNN KUBERNETES_PORT_443_TCP_ADDR = 10.96.0.1 KUBERNETES_SERVICE_HOST = 10.96.0.1 KUBERNETES_SERVICE_PORT KUBERNETES_SERVICE_PORT_HTTPS = 443 = 443 KUBERNETES_PORT = TCP: / / 10.96.0.1:443 KUBERNETES_PORT_443_TCP = TCP: / / 10.96.0.1:443 KUBERNETES_PORT_443_TCP_PROTO = TCP KUBERNETES_PORT_443_TCP_PORT = 443 NGINX_VERSION = 1.10.3-1 ~ Jessie HOME = / rootCopy the code
  • Go inside the container and executebashCommand to exit the containerexitCommand:
kubectl exec -ti $POD_NAME -- bash
Copy the code

Open exposure application

The default Pod cannot be accessed from outside the cluster. You need to create a Service and expose the port for external access.

  • Create a Service to expose kubernetes-nginx Deployment:
kubectl expose deployment/kubernetes-nginx --type="NodePort" --port 80
Copy the code
  • Check the status of all services in K8S:
kubectl get services
Copy the code
NAME TYPE cluster-ip external-ip PORT(S) AGE kubernetes ClusterIP 10.96.0.1 < None > 443/TCP 5h16m kubernetes-nginx NodePort 10.105.177.114 < None > 80:31891/TCP 5sCopy the code
  • To view details about the Service, passNodePortProperty to get exposed ports to the outside;
kubectl describe services/kubernetes-nginx
Copy the code
Name: kubernetes-nginx Namespace: default Labels: app=kubernetes-nginx Annotations: <none> Selector: App =kubernetes-nginx Type: NodePort IP Families: <none> IP: 10.106.227.54 IPs: 10.106.227.54 Port: <unset>  80/TCP
TargetPort:               80/TCP
NodePort:                 <unset> 30158/TCP Endpoints: 172.17.0.7:80 Session Affinity: None External Traffic Policy: Cluster Events: < None >Copy the code
  • Run the CURL command to pass the commandMinikube IP:NodePort IPYou can access the Nginx service, at which point the Nginx home page information will be printed;
curl $(minikube ip):30158
Copy the code
<! DOCTYPEhtml>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
Copy the code

Use of labels

Resources (such as Deployment, Pod, Service, and so on) can be easily managed by adding labels to them.

  • Look at the labels included in Deployment;
kubectl describe deployment
Copy the code
Name:                   kubernetes-nginx
Namespace:              default
CreationTimestamp:      Tue, 05 Jan 2021 13:57:46 +0800
Labels:                 app=kubernetes-nginx
Annotations:            deployment.kubernetes.io/revision: 1
Selector:               app=kubernetes-nginx
Replicas:               1 desired | 1 updated | 1 total | 1 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Copy the code
  • Query Pod by Label:
kubectl get pods -l app=kubernetes-nginx
Copy the code
NAME                                READY   STATUS    RESTARTS   AGE
kubernetes-nginx-78bcc44665-8fnnn   1/1     Running   1          21h
Copy the code
  • Query Service by Label:
kubectl get services -l app=kubernetes-nginx
Copy the code
NAME TYPE cluster-ip external-ip PORT(S) AGE kubernetes-nginx NodePort 10.106.227.54 < None > 80:30158/TCP 4m44sCopy the code
  • Add Label to Pod:
kubectl label pod $POD_NAME version=v1
Copy the code
  • To view Pod details, you can view Label information:
kubectl describe pods $POD_NAME
Copy the code
Name:         kubernetes-nginx-78bcc44665-8fnnn
Namespace:    default
Priority:     0
Node:         minikube/192.168.49.2
Start Time:   Tue, 05 Jan 2021 13:57:46 +0800
Labels:       app=kubernetes-nginx
              pod-template-hash=78bcc44665
              version=v1
Copy the code
  • Query Pod by Label:
kubectl get pods -l version=v1
Copy the code
  • Delete service by Label:
kubectl delete service -l app=kubernetes-nginx
Copy the code
NAME TYPE cluster-ip external-ip PORT(S) AGE Kubernetes ClusterIP 10.96.0.1 < None > 443/TCP 30hCopy the code

Visual management

Dashboard is a web-based K8S user interface. You can use Dashboard to deploy container applications to K8S clusters, troubleshoot container applications, and manage cluster resources.

  • View the built-in Minikube plugin, Dashboard plugin is not enabled by default:
minikube addons list
Copy the code
|-----------------------------|----------|--------------| | ADDON NAME | PROFILE | STATUS | |-----------------------------|----------|--------------| | dashboard | minikube | disabled | | default-storageclass | Minikube | enabled ✅ | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- - |Copy the code
  • Enable the Dashboard plugin:
minikube addons enable dashboard
Copy the code
  • Enable Dashboard and pass--urlParameter does not open the admin page and the access path is available on the console:
minikube dashboard --url
Copy the code
* Verifying dashboard health ...
* Launching proxy ...
* Verifying proxy health ...
http://127.0.0.1:44469/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
Copy the code
  • To access Dashboard from outside, you need to set up the proxy using Kubectl,--addressSet to your server address;
kubectl proxy --port=44469 --address='192.168.5.94' --accept-hosts='^. *' &
Copy the code
  • You need to enable the firewall port to access the server from the outside.
Switch to user root
su -
# open port
firewall-cmd --zone=public --add-port=44469/tcp --permanent
# restart firewall
firewall-cmd --reload
Copy the code
  • You can access the Dashboard using the following address:
http://192.168.5.94:44469/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy/
Copy the code
  • View the status of resources in the K8S cluster.

  • Create K8S resources with yamL script:

  • View status information for all pods in K8S. More buttons to view container logs and execute internal commands.

conclusion

When our application needs to be deployed on multiple physical machines, the traditional approach is to deploy one physical machine at a time. If we use K8S, we can think of these physical machines as a cluster and just deploy the application to the cluster through K8S, without worrying about the deployment details of the physical machine. In addition, the K8S provides functions such as horizontal capacity expansion, automatic packing, and automatic repair, greatly reducing the workload of application cluster deployment.

The resources

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

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