Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to deploy applications in Kubernetes

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)05/31 Report--

In this issue, the editor will bring you about how to deploy applications in Kubernetes. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Build a Spring Boot project through Eclipse, hereinafter referred to as demo, where the property file application-k8s.properties that connects to mysql is as follows:

Spring.datasource.url=jdbc:mysql://$ {MYSQL_SERVICE_HOST:127.0.0.1}: ${MYSQL_SERVICE_PORT:3306} / ${MYSQL_DATABASE:demo} spring.datasource.username=$ {MYSQL_ROOT_USER:root} spring.datasource.password=$ {MYSQL_ROOT_PASSWORD:123456} spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect spring.jpa.database = MYSQL # Show or not log for each sql Query spring.jpa.show-sql = true # Hibernate ddl auto (create Create-drop, update) spring.jpa.hibernate.ddl-auto = update

We specify the connection parameters of the database through environment variables, where:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Hostname or IP address of MYSQL_SERVICE_HOST:mysql

Port number of MYSQL_SERVICE_PORT:mysql

MYSQL_DATABASE: the name of the database that connects to mysql

Root user name of MYSQL_ROOT_USER:mysql

MYSQL_ROOT_PASSWORD:mysql 's root username and password

Package the demo into a jar file and upload it to the private Registry as a Docker Image made by Dockerfile.

Package jar Fil

Mvn package-Dmaven.test.skip=true INFO] Scanning for projects... [INFO] [INFO]--

< com.example:demo >

-- [INFO] Building demo 0.0.1 [INFO]-- [jar]-- [INFO] [INFO]- -maven-resources-plugin:3.1.0:resources (default-resources) @ demo-[INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 4 resources [INFO] Copying 0 resource [INFO] [INFO]-maven-compiler-plugin:3.8.0:compile (default-compile) @ demo-[INFO] Nothing to compile-all classes are up to date [INFO] [INFO]-maven-resources-plugin:3.1.0:testResources (default-testResources) @ demo-- [INFO] Not copying test resources [INFO] [INFO]-maven-compiler-plugin : 3.8.0:testCompile (default-testCompile) @ demo-[INFO] Not compiling test sources [INFO] [INFO]-maven-surefire-plugin:2.22.1:test (default-test) @ demo-[INFO] Tests are skipped. [INFO] [INFO]-maven-jar-plugin:3.1.1:jar (default-jar) @ demo-[INFO] Building jar: / Users/xiaobaoqiang/workspace/demo/spring-boot/target/demo.jar [INFO] [INFO]-spring-boot-maven-plugin:2.1.3.RELEASE:repackage (repackage) @ demo-- [INFO] Replacing main artifact with repackaged archive [INFO]- -[INFO] BUILD SUCCESS [INFO]- [INFO] Total time: 1.731 s [INFO] Finished at: 2019-03-31T12:33:52+08:00 [INFO]-

Dockerfile is as follows:

# base image FROM daocloud.io/java:8 # MAINTAINER MAINTAINER xiaobaoqiang@163.com # add demo.jar to docker tmp folder ADD. / demo.jar / tmp # run demo.jar package CMD ["java", "- jar", "/ tmp/demo.jar"] EXPOSE 9999

Make a Docker image

Docker build-t 10.0.0.10:5000/app/demo:v2.0. Sending build context to Docker daemon 44.18 MB Step 1 tmp 5: FROM daocloud.io/java:8-- > d23bdf5b1b1b Step 2 ADD 5: MAINTAINER xiaobaoqiang@163.com-> Using cache-- > 6a8e7ffcb8b7 Step 3 tmp 5: ADD. / demo.jar / tmp-> 11bc5f618c77 Removing intermediate container c3942d277805 Step 4 jar 5: CMD java-jar / tmp/demo.jar-- > Running in f877685bb056-> cb08fcc6b0a1 Removing intermediate container f877685bb056 Step 5 hand 5: EXPOSE 9999 > Running in 86a145142954-- > 189f73beb27a Removing intermediate container 86a145142954 Successfully built 189f73beb27a

View Docker image

Docker images REPOSITORY TAG IMAGE ID CREATED SIZE 10.0.0.10:5000/app/demo v2.0 189f73beb27a About an hour ago 687 MB

Push the created Docker image to the private Registry

Docker push 10.0.0.10:5000/app/demo:v2.0 The push refers to a repository [10.0.0.10:5000/app/demo] 6a6b9dbfc663: Pushed 35c20f26d188: Pushed c3fe59dd9556: Pushed 6ed1a81ba5b6: Pushed a3483ce177ce: Pushed ce6c8756685b: Pushed 30339f20ced0: Pushed 0eb22bfb707d: Pushed a2ae92ffcd29: Pushed v2.0: digest: sha256:7296321564a7ace0bf1f2e8099fb7e0e01610efec5e1d1fec0c877b236bc0f5f size: 2212

Now that our demo image is ready, let's start preparing the mysql image.

As the speed of the Docker Hub network abroad is relatively slow, we pull an image of mysql from the domestic Docker Hub to the local

Docker pull daocloud.io/library/mysql:5.7.4

Tag the mysql image and push it to our private Registry

Docker tag daocloud.io/library/mysql:5.7.4 10.0.0.10:5000/library/mysql:5.7.4 docker push 10.0.0.10:5000/library/mysql:5.7.4 The push refers to a repository [10.0.0.10:5000/library/mysql] 5f70bf18a086: Pushed 903c114b758c: Pushed c8c909bc9ac1: Pushed 6f19f89d53b4: Pushed 6e82deab235b: Pushed ca60b5cb617c: Pushed ac906c9ec95d: Pushed 4c816744690c: Pushed 5.7.4: digest: sha256:afe1630e8c9bd318a5e72b2536c2daacb96b8135cc2c6d3465262b5c7b7d1831 size: 3846

At this point, our mysql image is also ready. Let's deploy our demo application and mysql.

Create the deployment yaml file mysql-deployment.yaml for mysql

ApiVersion: v1 kind: Service metadata: name: mysql labels: app: mysql spec:-port: 3306 selector: app: mysql clusterIP: None-- apiVersion: apps/v1 # for k8s versions before 1.9.0 use apps/v1beta2 and before 1.8.0 use extensions/v1beta1 kind: Deployment metadata: name: mysql labels: app: mysql spec: selector: matchLabels: app: mysql template: metadata: labels: app: mysql spec: containers:-image: 10 .0.0.10: 5000/library/mysql:5.7.4 name: mysql env:-name: MYSQL_ROOT_PASSWORD value: "123456"-name: MYSQL_DATABASE value: "demo" livenessProbe: tcpSocket: port: 3306 ports:-containerPort: 3306 name: mysql

Some parameters are initialized with environment variables:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

MYSQL_ROOT_PASSWORD is the root password of mysql

MYSQL_DATABASE is the database created by default after mysql starts.

Create the yaml file demo-mysql-k8s.yaml for demo application deployment

#-Demo Deployment-# kind: Deployment apiVersion: apps/v1 metadata: labels: name: demo name: demo spec: selector: matchLabels: app: demo template: metadata: labels: app: demo spec: containers:-name: demo image: 10.0.0.10:5000/app/demo:v2.0 ports: -containerPort: 9999 protocol: TCP env:-name: MYSQL_SERVICE_HOST value: '172.18.45.2'-name: MYSQL_SERVICE_PORT value: "3306"-name: MYSQL_DATABASE value: "demo"-name: MYSQL_ROOT_USER value: "root"-name: MYSQL_ROOT_PASSWORD value: "123456" livenessProbe: httpGet: scheme: HTTP path: / service/v1/demo port: 9999 initialDelaySeconds: 30 timeoutSeconds: 30-- #-Demo Service-# kind: Service apiVersion: v1 metadata: labels: name: demo name: demo spec: ports:-port: 9900 targetPort: 9999 selector: app: demo

Some parameters are initialized with the environment variable, which corresponds to the environment variable name in application-k8s.properties, where MYSQL_SERVICE_HOST is the enpoint IP address after mysql deployment.

Start deployment from the kubectl command line

Kubectl apply-f mysql-deployment.yaml service/mysql created deployment.apps/mysql created

Check the endpoint IP address of mysql

Kubectl get service NAME TYPE CLUSTER-IP EXTERNAL-IP PORT (S) AGE kubernetes ClusterIP 172.10.12.1 443/TCP 63d mysql ClusterIP None 3306/TCP 121m kubectl describe service mysql Name: mysql Namespace: default Labels: app=mysql Annotations: kubectl.kubernetes.io/last-applied-configuration: {"apiVersion": "v1", "kind": "Service", "metadata": {"annotations": {}, "labels": {"app": "mysql"}, "name": "mysql", "namespace": "default"} "spec": {"c. Selector: app=mysql Type: ClusterIP IP: None Port: 3306/TCP TargetPort: 3306/TCP Endpoints: 172.18.45.2:3306 Session Affinity: None Events:

You can see that the enpoint IP address of mysql is 172.18.45.2 and the port number is 3306.

Deploy demo applications

Kubectl apply-f demo-mysql-k8s.yaml deployment.apps/demo created service/demo created kubectl get pods NAME READY STATUS RESTARTS AGE demo-d4cd5bfdd-8qpfw 1 demo-mysql-k8s.yaml deployment.apps/demo created service/demo created kubectl get pods NAME READY STATUS RESTARTS AGE demo-d4cd5bfdd-8qpfw 1 Running 0 3s mysql-6f76465564-j8dq2 1 Running 0 60m

View the log started by demo

Kubectl logs demo-d4cd5bfdd-8qpfw. _ _ _ / / _ _ _ (() _ _ _ (()\ _ _ _ |'_ | |'_ / _ _ `|\ / _ _ _ | | | (_ |)'| _ _ _ |. _ _ | _ | | _ | _ | | _\ _ _ | | / = | _ | = | _ _ / = /: Spring Boot:: (v2.1.3.RELEASE) 2019-03-31 103 INFO 55 INFO 08.236 Starting DemoApplication 1-[main] com.example.demo.DemoApplication: Starting DemoApplication v0.0.1 on demo-d4cd5bfdd-8qpfw with PID 1 (/ tmp/demo.jar started by root in /) 2019-03-31 0355 Spring Boot 08.245 INFO 1-- [main] ] com.example.demo.DemoApplication: The following profiles are active: K8s 2019-03-31 0355 INFO 09.149 INFO 1-[main] .s.d.r.c.RepositoryConfigurationDelegate: Bootstrapping Spring Data repositories in DEFAULT mode. 2019-03-31 03-31 103 INFO 55 Finished Spring Data repository scanning in 51ms 09.204 Delegate 1-[main] .s.d.r.c.RepositoryConfigurationDelegate. Found 1 repository interfaces. 2019-03-31 03-31 03 o.s.b.w.embedded.tomcat.TomcatWebServer 55 INFO 09.516 INFO 1-[main] trationDelegate$BeanPostProcessorChecker: Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$eb5e36c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-03-31 03-31 03-31 55 o.s.b.w.embedded.tomcat.TomcatWebServer 09.782 INFO 1-- [main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat initialized with port (s): 9999 (http) 2019-03-31 03o.apache.catalina.core.StandardService main o.apache.catalina.core.StandardService: Starting service [Tomcat] 2019-03-31 103 INFO 09.807 INFO 1-- [main] org.apache.catalina.core.StandardEngine: Starting Servlet engine: [Apache Tomcat/9.0.16] 2019-03-31 031515 INFO 1-- [main] o.a.catalina.core.AprLifecycleListener: The APR based Apache Tomcat Native library which allows optimal performance in Production environments was not found on the java.library.path: [/ usr/java/packages/lib/amd64:/usr/lib/x86_64-linux-gnu/jni:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu:/usr/lib/jni:/lib:/usr/lib] 2019-03-31 103 INFO 55 INFO 09.881-[main] o.a.c.c..localhost. [ /]: Initializing Spring embedded WebApplicationContext 2019-03-31 103 INFO 55 INFO 09.881 INFO 1-[main] o.s.web.context.ContextLoader: Root WebApplicationContext: initialization completed in 1593 ms 2019-03-31 03 03-31 03 Paradigm 55 purl 10.129 INFO 1-[main] o.hibernate.jpa.internal.util.LogHelper: HHH000204: Processing PersistenceUnitInfo [name: default...] 2019-03-31 03 03 purl 5515 10.179 INFO 1-[main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final} 2019-03-31 103 INFO 55 INFO 1-[main] org.hibernate.cfg.Environment: HHH000206: hibernate.properties not found 2019-03-31 03 Paradigm 55 HHH000412 10.284 INFO 1-[main] o.hibernate.annotations.common.Version: HCANN000001: Hibernate Commons Annotations {5.0.4.Final} 2019-03-31 103 55 INFO 10.444 INFO 1-- [main] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Starting... 2019-03-3103 com.zaxxer.hikari.HikariDataSource 55 HikariPool-1 20.542 INFO 1-[main] com.zaxxer.hikari.HikariDataSource: HikariPool-1-Start completed. 2019-03-31 103 INFO 55 HHH000400 20.551 INFO 1-[main] org.hibernate.dialect.Dialect: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect Hibernate: create table demo_users (id integer not null, birth_day datetime, create_date datetime, email varchar, name varchar, sex integer Primary key (id)) engine=MyISAM Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM Hibernate: insert into hibernate_sequence values (1) 2019-03-3103 INFO 5520. 984 INFO 1-[main] j.LocalContainerEntityManagerFactoryBean: Initialized JPA EntityManagerFactory for persistence unit 'default' 2019-03-31 03 Vega 55 default' 21.315 WARN 1-[main] aWebConfiguration$JpaWebMvcConfiguration: spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2019-03-31 03-31 103 Revue 55 INFO 21.408 INFO 1-[main] pertySourcedRequestMappingHandlerMapping: Mapped URL path [/ v2/api-docs] onto method [public org.springframework.http.ResponseEntity springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation (java.lang.String) Javax.servlet.http.HttpServletRequest)] 2019-03-31 103 INFO 55 INFO 21.504 o.s.s.concurrent.ThreadPoolTaskExecutor: Initializing ExecutorService 'applicationTaskExecutor' 2019-03-31 03 javax.servlet.http.HttpServletRequest 55 Initializing ExecutorService 21.801 INFO 1-[main] d.s.w.p.DocumentationPluginsBootstrapper: Context refreshed 2019-03-31 103 V 55 INFO 21.821 INFO 1-- [main] d.s.w.p.DocumentationPluginsBootstrapper: Found 1 custom documentation plugin (s) 2019-03 -31 03 INFO 55 INFO 21.844 s.d.s.w.s.ApiListingReferenceScanner: Scanning for api listing references 2019-03-31 103 INFO 5522.118 INFO 1-[main] o.s.b.w.embedded.tomcat.TomcatWebServer: Tomcat started on port (s): 9999 (http) with context path '2019-03-31 03 V 55 INFO 1-- [main] com.example.demo.DemoApplication: Started DemoApplication in 14.323 seconds (JVM running for 14.62)

From the log, we can see that our demo application has connected to the mysql database, and our demo application starts normally.

Verification

Access our demo health check through Kubernetes's proxy

Kubectl proxy-- address='0.0.0.0'-- disable-filter=true & curl http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/demo {"author": "xiaobaoqiang", "title": "this isa demo", "version": "1.0"}

Write test data to the database through restful api

Curl-X POST "http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/user"-H" accept: application/json "- H" Content-Type: application/json "- d" {\ "birthDay\":\ "2019-03-31T04:03:43.259Z\",\ "createDate\":\ "2019-03-31T04:03:43.259Z\",\ "email\":\ "A1@test.com\" \ "name\":\ "A1\",\ "sex\": 0} "success curl-X POST" http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/user"-H "accept: application/json"-H "Content-Type: application/json"-d "{\" birthDay\ ":\" 2019-03-31T04:03:43.259Z\ " \ "createDate\":\ "2019-03-31T04:03:43.259Z\",\ "email\":\ "B2@test.com\",\ "name\":\ "B2\",\ "sex\": 1} "success

Query the data just written through restful api

Curl-X GET "http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/users"-H" accept: application/json [{"id": 1, "name": "A1", "email": "A1@test.com", "sex": 0, "birthDay": "2019-03-31T04:03:43.000+0000", "createDate": "2019-03-31T04:03:43.000+0000"}, {"id": 2 "name": "B2", "email": "B2@test.com", "sex": 1, "birthDay": "2019-03-31T04:03:43.000+0000", "createDate": "2019-03-31T04:03:43.000+0000"}]

You can see that the test data just written has been queried.

View the data of the database from the command line

Kubectl get pod NAME READY STATUS RESTARTS AGE demo-d4cd5bfdd-8qpfw 1 Running 0 7m54s mysql-6f76465564-j8dq2 1 7m54s mysql-6f76465564-j8dq2 1 Running 0 67m kubectl exec-it mysql-6f76465564-j8dq2 bash root@mysql-6f76465564-j8dq2:/usr/local/mysql# mysql- u root-p Enter password: Welcome to the MySQL monitor. Commands end with; or\ g. Your MySQL connection id is 422 Server version: 5.7.4-m14 MySQL Community Server (GPL) Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or'\ h' for help. Type'\ c'to clear the current input statement. Mysql > mysql > show databases; +-+ | Database | +-+ | information_schema | | demo | | mysql | | performance_schema | +-+ 4 rows in set (0.00 sec) mysql > use demo Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with-A Database changed mysql > show tables; +-+ | Tables_in_demo | +-+ | demo_users | | hibernate_sequence | +-+ 2 rows in set (0.00 sec) mysql > select * from demo_users +-- +-+ | id | birth_day | create_date | email | name | sex | + -- + | 1 | 2019-03-31 04:03:43 | 2019-03-31 04:03:43 | A1@test.com | A1 | 0 | 2 | 2019-03-31 04:03:43 | 2019-03-31 04:03:43 | B2@test.com | B2 | | 1 | +-+-+ 2 rows in set (0.00 sec) |

From the mysql command line, we can see that the test data has been saved to the database.

The above is how to deploy the application in the Kubernetes shared by the editor. If you happen to have similar doubts, please refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report