I deployed the springboot application to k8s. How does it feel like docker!

Time:2022-1-8

To deploy a complex microservice project to k8s, we must first learn to deploy a single springboot application. Today, let’s talk about how to deploy springboot applications to k8s, which is very similar to using docker compose deployment. I hope it will be helpful to you!

Springboot e-commerce project Mall (40K + star) address:https://github.com/macrozheng/mall

Pre school preparation

Learning this article requires some k8s foundation. Friends who do not understand k8s can refer to the following articles.

Push image to docker hub

Before, we all built our own image warehouse. This time, we upload the image to the docker hub in another way.

I deployed the springboot application to k8s. How does it feel like docker!

  • Before deploying the applicationmall-tiny-fabricItem, modify firstpom.xmlFile, which mainly adds the authentication information of docker hub and modifies the image prefix. The specific contents are as follows:;
<configuration>
    <!--  Docker remote management address -- >
    <dockerHost>http://192.168.5.94:2375</dockerHost>
    <!--  Add authentication information -- >
    <authConfig>
        <push>
            <!-- Docker hub user name -- >
            <username>macrodocker</username>
            <!-- Docker hub password -- >
            <password>xxx</password>
        </push>
    </authConfig>
    <images>
        <image>
            <!-- Modify the image prefix to docker hub user name -- >
            <name>macrodocker/${project.name}:${project.version}</name>
        </image>
     </images>
 </configuration>
  • Use after modificationpackageThe command packages the image to the Linux server before usingdocker:pushThe command pushes the image to the docker hub:

I deployed the springboot application to k8s. How does it feel like docker!

  • After the push is successful, you can see the image in the docker hub.

I deployed the springboot application to k8s. How does it feel like docker!

Application deployment

Next, we will deploy the application to k8s, including the deployment of springboot application and mysql.

Deploy MySQL

  • Add the profile firstmysql-deployment.yamlIt is used to create a deployment. For details, please refer to the notes;
apiVersion: apps/v1
kind: Deployment
metadata:
  #Specify the name of the deployment
  name: mysql-deployment
  #Specifies the label of the deployment 
  labels:
    app: mysql
spec:
  #Specifies the number of pod copies created 
  replicas: 1
  #Defines how to find pods to manage
  selector:
    #The management tag app is the pod of MySQL
    matchLabels:
      app: mysql
  #Specify the template for creating the pod
  template:
    metadata:
      #Tag pod with app: MySQL
      labels:
        app: mysql
    #Template specification of pod
    spec:
      containers:
        - name: mysql
          #Specify container mirroring
          image: mysql:5.7
          #Specify open ports
          ports:
            - containerPort: 3306
          #Setting environment variables
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: root
          #Using storage volumes
          volumeMounts:
            #Mount the storage volume to the internal path of the container
            - mountPath: /var/log/mysql
              name: log-volume
            - mountPath: /var/lib/mysql
              name: data-volume
            - mountPath: /etc/mysql
              name: conf-volume
      #Define storage volumes
      volumes:
        - name: log-volume
          #The hostpath type stores the path of the volume on the host
          hostPath:
            path: /home/docker/mydata/mysql/log
            #Create when directory does not exist
            type: DirectoryOrCreate
        - name: data-volume
          hostPath:
            path: /home/docker/mydata/mysql/data
            type: DirectoryOrCreate
        - name: conf-volume
          hostPath:
            path: /home/docker/mydata/mysql/conf
            type: DirectoryOrCreate
kubectl apply -f mysql-deployment.yaml
  • After running successfully, query the deployment and findmysql-deploymentReady;
[[email protected] k8s]$ kubectl get deployments
NAME                      READY   UP-TO-DATE   AVAILABLE   AGE
mysql-deployment          1/1     1            1           38s
nginx-volume-deployment   2/2     2            2           6d5h
  • If you want other pods to access MySQL through the service name, you need to create a service and add a configuration filemysql-service.yamlUsed to create service;
apiVersion: v1
kind: Service
metadata:
  #Define the service name. Other pods can be accessed through the service name as the domain name
  name: mysql-service
spec:
  #Specify the service type and expose the service through the static port on the node
  type: NodePort
  #The management tag app is the pod of MySQL
  selector:
    app: mysql
  ports:
    - name: http
      protocol: TCP
      port: 3306
      targetPort: 3306
      #Static port on node
      nodePort: 30306
  • Create a service by applying a configuration file;
kubectl apply -f mysql-service.yaml 
  • After running successfully, query the service and findmysql-serviceHas been exposed to the node’s30306The port is on;
[[email protected] k8s]$ kubectl get services
NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes      ClusterIP   10.96.0.1        <none>        443/TCP          7d23h
mysql-service   NodePort    10.107.189.51    <none>        3306:30306/TCP   7s
nginx-service   NodePort    10.101.171.181   <none>        80:30080/TCP     6d2h
  • You need to create a new one after deploymentmallDatabase and import related tables. Table address:https://github.com/macrozheng…
  • Here is a relatively simple method to import the database. Create a connection through Navicat and configure an SSH channel first;

I deployed the springboot application to k8s. How does it feel like docker!

  • After that, we can access the database in minikube just like accessing the database on the Linux server. We can directly add the database IP and port in minikube.

I deployed the springboot application to k8s. How does it feel like docker!

Deploying springboot applications

  • Add the profile firstmall-tiny-fabric-deployment.yamlIt is used to create deployment. Here, we can override the default configuration in springboot through environment variables;
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mall-tiny-fabric-deployment
  labels:
    app: mall-tiny-fabric
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mall-tiny-fabric
  template:
    metadata:
      labels:
        app: mall-tiny-fabric
    spec:
      containers:
        - name: mall-tiny-fabric
          #Specify the image address in the docker hub
          image: macrodocker/mall-tiny-fabric:0.0.1-SNAPSHOT
          ports:
            - containerPort: 8080
          env:
            #Specify the database connection address
            - name: spring.datasource.url
              value: jdbc:mysql://mysql-service:3306/mall?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
            #Specify log file path
            - name: logging.path
              value: /var/logs
          volumeMounts:
            - mountPath: /var/logs
              name: log-volume
      volumes:
        - name: log-volume
          hostPath:
            path: /home/docker/mydata/app/mall-tiny-fabric/logs
            type: DirectoryOrCreate
  • Create a deployment by applying a configuration file;
kubectl apply -f mall-tiny-fabric-deployment.yaml
  • We can passkubectl logsCommand to view the application startup log;
[[email protected] k8s]$ kubectl get pods
NAME                                           READY   STATUS    RESTARTS   AGE
mall-tiny-fabric-deployment-8684857dff-pnz2t   1/1     Running   0          47s
mysql-deployment-5dccc96ccf-sfxvg              1/1     Running   0          25m
nginx-volume-deployment-6f6c89976d-nv2rn       1/1     Running   4          6d6h
nginx-volume-deployment-6f6c89976d-tmhc5       1/1     Running   4          6d5h
[[email protected] k8s]$ kubectl logs -f mall-tiny-fabric-deployment-8684857dff-pnz2t
  • If you want to access the springboot application from outside, you need to create a service and add a configuration filemall-tiny-fabric-service.yamlUsed to create service;
apiVersion: v1
kind: Service
metadata:
  name: mall-tiny-fabric-service
spec:
  type: NodePort
  selector:
    app: mall-tiny-fabric
  ports:
    - name: http
      protocol: TCP
      port: 8080
      targetPort: 8080
      #Static port on node
      nodePort: 30180
  • Create a service by applying a configuration file;
kubectl apply -f mall-tiny-fabric-service.yaml
  • At this time, the service has been exposed to the node30180The port is on;
[[email protected] k8s]$ kubectl get services
NAME                       TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
kubernetes                 ClusterIP   10.96.0.1        <none>        443/TCP          7d23h
mall-tiny-fabric-service   NodePort    10.100.112.84    <none>        8080:30180/TCP   5s
mysql-service              NodePort    10.107.189.51    <none>        3306:30306/TCP   13m
nginx-service              NodePort    10.101.171.181   <none>        80:30080/TCP     6d2h
  • On Linux servers, we cancurlCommand to access the swagger page of the next project, but you can only view the returned string of HTML code.
curl $(minikube ip):30180/swagger-ui.html

External access application

Since the k8s node installed with minikube is in the Intranet environment of the Linux server and cannot be accessed directly from the outside, we need to install an nginx reverse agent to access it.

  • First, we need to install nginx. If you are not familiar with nginx, you can directly refer to this article:There must be something you don’t know about these wonderful functions of nginx
  • After installation, add a configuration file of nginx, where my configuration path is/mydata/nginx/conf/conf.d/, used tomall-tiny.macrozheng.comThe domain name access proxy is applied to the springboot application in k8s,proxy_passFor abovecurlThe path used;
server {
    listen       80;
    server_ name  mall-tiny. macrozheng. com; # Modify domain name

    location / {
        proxy_set_header Host $host:$server_port;
        proxy_ pass    http://192.168.49.2:30180 # Change to proxy service address
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}
  • Restart the nginx service, modify the local host file accessing the Linux server, and add the following records;
192.168.5.94 mall-tiny.macrozheng.com

I deployed the springboot application to k8s. How does it feel like docker!

summary

By deploying the springboot application to k8s, we can find that there are many similarities between deploying on k8s and docker. Many deployment scripts on k8s can be directly translated using docker compose, which is very similar. If you have used docker before, you can easily start k8s!

Project source code address

https://github.com/macrozheng…

This article GitHubhttps://github.com/macrozheng/mall-learningAlready included, welcome to star!

Recommended Today

Proper memory alignment in go language

problem type Part1 struct { a bool b int32 c int8 d int64 e byte } Before we start, I want you to calculatePart1What is the total occupancy size? func main() { fmt.Printf(“bool size: %d\n”, unsafe.Sizeof(bool(true))) fmt.Printf(“int32 size: %d\n”, unsafe.Sizeof(int32(0))) fmt.Printf(“int8 size: %d\n”, unsafe.Sizeof(int8(0))) fmt.Printf(“int64 size: %d\n”, unsafe.Sizeof(int64(0))) fmt.Printf(“byte size: %d\n”, unsafe.Sizeof(byte(0))) fmt.Printf(“string size: %d\n”, […]