当前位置:主页 > 查看内容

一个简单的Kubernetes应用部署示例

发布时间:2021-06-09 00:00| 位朋友查看

简介:说明 我们通过一个简单的示例来说明如何在Kubernets中部署一个应用, 一个Spring Boot项目提供数据库的增删改查操作 一个Mysql数据库持久化数据 通过Eclipse构建一个Spring Boot项目以下简称demo,其中连接mysql的property文件application-k8s.properties内……

说明

我们通过一个简单的示例来说明如何在Kubernets中部署一个应用,

  1. 一个Spring Boot项目提供数据库的增删改查操作
  2. 一个Mysql数据库持久化数据

通过Eclipse构建一个Spring Boot项目以下简称demo,其中连接mysql的property文件application-k8s.properties内容如下:

  1. spring.datasource.url=jdbc:mysql://${MYSQL_SERVICE_HOST:127.0.0.1}:${MYSQL_SERVICE_PORT:3306}/${MYSQL_DATABASE:demo} 
  2. spring.datasource.username=${MYSQL_ROOT_USER:root} 
  3. spring.datasource.password=${MYSQL_ROOT_PASSWORD:123456} 
  4. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 
  5. spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect 
  6. ​ 
  7. spring.jpa.database = MYSQL  
  8. # Show or not log for each sql query  
  9. spring.jpa.show-sql = true  
  10. # Hibernate ddl auto (createcreate-dropupdate)  
  11. spring.jpa.hibernate.ddl-auto = update 

我们通过环境变量来指定数据库的连接参数,其中:

  1. MYSQL_SERVICE_HOST:mysql的hostname或者IP地址
  2. MYSQL_SERVICE_PORT:mysql的端口号
  3. MYSQL_DATABASE:连接mysql的数据库名
  4. MYSQL_ROOT_USER:mysql的root用户名
  5. MYSQL_ROOT_PASSWORD:mysql的root用户名密码

将demo打包成jar文件,并且用Dockerfile制作成Docker Image上传到私有Registry。

打包jar文件

  1. mvn package -Dmaven.test.skip=true 
  2. INFO] Scanning for projects... 
  3. [INFO]  
  4. [INFO] --------------------------< com.example:demo >-------------------------- 
  5. [INFO] Building demo 0.0.1 
  6. [INFO] --------------------------------[ jar ]--------------------------------- 
  7. [INFO]  
  8. [INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ demo --- 
  9. [INFO] Using 'UTF-8' encoding to copy filtered resources. 
  10. [INFO] Copying 4 resources 
  11. [INFO] Copying 0 resource 
  12. [INFO]  
  13. [INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ demo --- 
  14. [INFO] Nothing to compile - all classes are up to date 
  15. [INFO]  
  16. [INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ demo --- 
  17. [INFO] Not copying test resources 
  18. [INFO]  
  19. [INFO] --- maven-compiler-plugin:3.8.0:testCompile (default-testCompile) @ demo --- 
  20. [INFO] Not compiling test sources 
  21. [INFO]  
  22. [INFO] --- maven-surefire-plugin:2.22.1:test (default-test) @ demo --- 
  23. [INFO] Tests are skipped. 
  24. [INFO]  
  25. [INFO] --- maven-jar-plugin:3.1.1:jar (default-jar) @ demo --- 
  26. [INFO] Building jar: /Users/xiaobaoqiang/workspace/demo/spring-boot/target/demo.jar 
  27. [INFO]  
  28. [INFO] --- spring-boot-maven-plugin:2.1.3.RELEASE:repackage (repackage) @ demo --- 
  29. [INFO] Replacing main artifact with repackaged archive 
  30. [INFO] ------------------------------------------------------------------------ 
  31. [INFO] BUILD SUCCESS 
  32. [INFO] ------------------------------------------------------------------------ 
  33. [INFO] Total time: 1.731 s 
  34. [INFO] Finished at: 2019-03-31T12:33:52+08:00 
  35. [INFO] ------------------------------------------------------------------------ 

Dockerfile如下:

  1. # base image 
  2. FROM daocloud.io/java:8 
  3. ​ 
  4. # MAINTAINER 
  5. MAINTAINER xiaobaoqiang@163.com 
  6. ​ 
  7. add demo.jar to docker tmp folder 
  8. ADD ./demo.jar /tmp 
  9. ​ 
  10. # run demo.jar package 
  11. CMD ["java""-jar""/tmp/demo.jar"
  12. ​ 
  13. EXPOSE 9999 

制作Docker镜像

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

查看Docker镜像

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

将制作好的Docker镜像push到私有Registry

  1. docker push 10.0.0.10:5000/app/demo:v2.0 
  2. The push refers to a repository [10.0.0.10:5000/app/demo] 
  3. 6a6b9dbfc663: Pushed  
  4. 35c20f26d188: Pushed  
  5. c3fe59dd9556: Pushed  
  6. 6ed1a81ba5b6: Pushed  
  7. a3483ce177ce: Pushed  
  8. ce6c8756685b: Pushed  
  9. 30339f20ced0: Pushed  
  10. 0eb22bfb707d: Pushed  
  11. a2ae92ffcd29: Pushed  
  12. v2.0: digest: sha256:7296321564a7ace0bf1f2e8099fb7e0e01610efec5e1d1fec0c877b236bc0f5f size: 2212 

到此,我们的demo镜像已经准备就绪,下面开始准备mysql镜像。

由于国外的Docker Hub网速比较慢,我们从国内的Docker Hub拉取一个mysql的镜像到本地

  1. docker pull daocloud.io/library/mysql:5.7.4 

将mysql镜像打tag,并且push到我们的私有Registry

  1. docker tag daocloud.io/library/mysql:5.7.4 10.0.0.10:5000/library/mysql:5.7.4 
  2. docker push 10.0.0.10:5000/library/mysql:5.7.4 
  3. The push refers to a repository [10.0.0.10:5000/library/mysql] 
  4. 5f70bf18a086: Pushed  
  5. 903c114b758c: Pushed  
  6. c8c909bc9ac1: Pushed  
  7. 6f19f89d53b4: Pushed  
  8. 6e82deab235b: Pushed  
  9. ca60b5cb617c: Pushed  
  10. ac906c9ec95d: Pushed  
  11. 4c816744690c: Pushed  
  12. 5.7.4: digest: sha256:afe1630e8c9bd318a5e72b2536c2daacb96b8135cc2c6d3465262b5c7b7d1831 size: 3846 

到此,我们mysql的镜像也准备就绪,下面开始部署我们的demo应用和mysql

创建mysql的部署yaml文件mysql-deployment.yaml

  1. apiVersion: v1 
  2. kind: Service 
  3. metadata: 
  4.  name: mysql 
  5.  labels: 
  6.  app: mysql 
  7. spec: 
  8.  ports: 
  9.  - port: 3306 
  10.  selector: 
  11.  app: mysql 
  12.  clusterIP: None 
  13.   
  14. --- 
  15. apiVersion: apps/v1 # for k8s versions before 1.9.0 use apps/v1beta2 and before 1.8.0 use extensions/v1beta1 
  16. kind: Deployment 
  17. metadata: 
  18.  name: mysql 
  19.  labels: 
  20.  app: mysql 
  21. spec: 
  22.  selector: 
  23.  matchLabels: 
  24.  app: mysql 
  25.  template: 
  26.  metadata: 
  27.  labels: 
  28.  app: mysql 
  29.  spec: 
  30.  containers: 
  31.  - image: 10.0.0.10:5000/library/mysql:5.7.4 
  32.  name: mysql 
  33.  env: 
  34.  - name: MYSQL_ROOT_PASSWORD 
  35.  value: "123456" 
  36.  - name: MYSQL_DATABASE 
  37.  value: "demo" 
  38.  livenessProbe: 
  39.  tcpSocket: 
  40.  port: 3306 
  41.  ports: 
  42.  - containerPort: 3306 
  43.  name: mysql 
  44. ​ 

通过环境变量初始化了一些参数:

  1. MYSQL_ROOT_PASSWORD为mysql的root密码
  2. MYSQL_DATABASE为mysql启动后默认创建的数据库

创建demo应用部署的yaml文件demo-mysql-k8s.yaml

  1. ------------------- Demo Deployment ------------------- # 
  2. kind: Deployment 
  3. apiVersion: apps/v1 
  4. metadata: 
  5.  labels: 
  6.  name: demo 
  7.  name: demo 
  8. spec:  
  9.  selector: 
  10.  matchLabels: 
  11.  app: demo 
  12.  template: 
  13.  metadata: 
  14.  labels: 
  15.  app: demo 
  16.  spec: 
  17.  containers: 
  18.  - name: demo 
  19.  image: 10.0.0.10:5000/app/demo:v2.0 
  20.  ports: 
  21.  - containerPort: 9999 
  22.  protocol: TCP 
  23.  env:  
  24.  - name: MYSQL_SERVICE_HOST 
  25.  value: '172.18.45.2' 
  26.  - name: MYSQL_SERVICE_PORT 
  27.  value: "3306" 
  28.  - name: MYSQL_DATABASE 
  29.  value: "demo" 
  30.  - name: MYSQL_ROOT_USER 
  31.  value: "root" 
  32.  - name: MYSQL_ROOT_PASSWORD 
  33.  value: "123456" 
  34.  livenessProbe: 
  35.  httpGet: 
  36.  scheme: HTTP 
  37.  path: /service/v1/demo 
  38.  port: 9999 
  39.  initialDelaySeconds: 30 
  40.  timeoutSeconds: 30 
  41. --- 
  42. ------------------- Demo Service ------------------- # 
  43. ​ 
  44. kind: Service 
  45. apiVersion: v1 
  46. metadata: 
  47.  labels: 
  48.  name: demo 
  49.  name: demo 
  50. spec:  
  51.  ports: 
  52.  - port: 9900 
  53.  targetPort: 9999 
  54.  selector: 
  55.  app: demo 
  56.   

通过环境变量初始化了一些参数,这些参数与application-k8s.properties中的环境变量名对应,其中MYSQL_SERVICE_HOST是mysql部署后的enpoint IP地址。

通过kubectl命令行开始部署

  1. kubectl apply -f mysql-deployment.yaml 
  2. service/mysql created 
  3. deployment.apps/mysql created 

查看mysql的endpoint IP地址

  1. kubectl get service 
  2. NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE 
  3. kubernetes ClusterIP 172.10.12.1 <none> 443/TCP 63d 
  4. mysql ClusterIP None <none> 3306/TCP 121m 
  5. ​ 
  6. kubectl describe service mysql 
  7. Name: mysql 
  8. Namespace: default 
  9. Labels: app=mysql 
  10. Annotations: kubectl.kubernetes.io/last-applied-configuration: 
  11.  {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"mysql"},"name":"mysql","namespace":"default"},"spec":{"c... 
  12. Selector: app=mysql 
  13. Type: ClusterIP 
  14. IP: None 
  15. Port: <unset> 3306/TCP 
  16. TargetPort: 3306/TCP 
  17. Endpoints: 172.18.45.2:3306 
  18. Session Affinity: None 
  19. Events: <none> 
  20. ​ 

可以看到mysql的enpoint IP地址是172.18.45.2,端口号是3306。

部署demo应用

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

查看demo启动的日志

  1. kubectl logs demo-d4cd5bfdd-8qpfw 
  2. ​ 
  3.  . ____ _ __ _ _ 
  4.  /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ 
  5. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ 
  6.  \\/ ___)| |_)| | | | | || (_| | ) ) ) ) 
  7.  ' |____| .__|_| |_|_| |_\__, | / / / / 
  8.  =========|_|==============|___/=/_/_/_/ 
  9.  :: Spring Boot :: (v2.1.3.RELEASE) 
  10. ​ 
  11. 2019-03-31 03:55:08.236 INFO 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 /) 
  12. 2019-03-31 03:55:08.245 INFO 1 --- [ main] com.example.demo.DemoApplication : The following profiles are active: k8s 
  13. 2019-03-31 03:55:09.149 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode. 
  14. 2019-03-31 03:55:09.204 INFO 1 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 51ms. Found 1 repository interfaces. 
  15. 2019-03-31 03:55: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) 
  16. 2019-03-31 03:55:09.782 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 9999 (http) 
  17. 2019-03-31 03:55:09.807 INFO 1 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 
  18. 2019-03-31 03:55:09.807 INFO 1 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.16] 
  19. 2019-03-31 03:55:09.814 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] 
  20. 2019-03-31 03:55:09.881 INFO 1 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 
  21. 2019-03-31 03:55:09.881 INFO 1 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1593 ms 
  22. 2019-03-31 03:55:10.129 INFO 1 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [ 
  23.  namedefault 
  24.  ...] 
  25. 2019-03-31 03:55:10.179 INFO 1 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.3.7.Final} 
  26. 2019-03-31 03:55:10.180 INFO 1 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found 
  27. 2019-03-31 03:55:10.284 INFO 1 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.4.Final} 
  28. 2019-03-31 03:55:10.444 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting... 
  29. 2019-03-31 03:55:20.542 INFO 1 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed. 
  30. 2019-03-31 03:55:20.551 INFO 1 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect 
  31. Hibernate: create table demo_users (id integer not null, birth_day datetime, create_date datetime, email varchar(255), name varchar(255), sex integerprimary key (id)) engine=MyISAM 
  32. Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM 
  33. Hibernate: insert into hibernate_sequence values ( 1 ) 
  34. 2019-03-31 03:55:20.984 INFO 1 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 
  35. 2019-03-31 03:55: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 
  36. 2019-03-31 03:55:21.408 INFO 1 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [public org.springframework.http.ResponseEntity<springfox.documentation.spring.web.json.Json> springfox.documentation.swagger2.web.Swagger2Controller.getDocumentation(java.lang.String,javax.servlet.http.HttpServletRequest)] 
  37. 2019-03-31 03:55:21.504 INFO 1 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 
  38. 2019-03-31 03:55:21.801 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed 
  39. 2019-03-31 03:55:21.821 INFO 1 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s) 
  40. 2019-03-31 03:55:21.844 INFO 1 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references 
  41. 2019-03-31 03:55:22.118 INFO 1 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 9999 (http) with context path '' 
  42. 2019-03-31 03:55:22.119 INFO 1 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 14.323 seconds (JVM running for 14.62) 

通过日志可以看到我们的demo应用已经连接到mysql数据库,我们的demo应用启动正常。

验证

通过Kubernetes的proxy访问我们的demo的health check

  1. kubectl proxy --address='0.0.0.0' --disable-filter=true & 
  2. ​ 
  3. curl http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/demo 
  4. {"author":"xiaobaoqiang","title":"this is a demo","version":"1.0"

通过restful api向数据库写入测试数据

  1. 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}" 
  2. success 
  3. ​ 
  4. 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}" 
  5. success  

通过restful api查询刚才写入的数据

  1. curl -X GET "http://10.0.0.10:8001/api/v1/namespaces/default/services/demo/proxy/service/v1/users" -H "accept: application/json" 
  2. [{"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"}] 

可以看到已经查询到刚才写入的测试数据。

通过命令行查看数据库的数据

  1. kubectl get pod 
  2. NAME READY STATUS RESTARTS AGE 
  3. demo-d4cd5bfdd-8qpfw 1/1 Running 0 7m54s 
  4. mysql-6f76465564-j8dq2 1/1 Running 0 67m 
  5. ​ 
  6. kubectl exec -it mysql-6f76465564-j8dq2 bash 
  7. root@mysql-6f76465564-j8dq2:/usr/local/mysql# mysql -u root -p 
  8. Enter password:  
  9. Welcome to the MySQL monitor. Commands end with ; or \g. 
  10. Your MySQL connection id is 422 
  11. Server version: 5.7.4-m14 MySQL Community Server (GPL) 
  12. ​ 
  13. Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved. 
  14. ​ 
  15. Oracle is a registered trademark of Oracle Corporation and/or its 
  16. affiliates. Other names may be trademarks of their respective 
  17. owners. 
  18. ​ 
  19. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. 
  20. ​ 
  21. mysql>  
  22. mysql> show databases; 
  23. +--------------------+ 
  24. Database | 
  25. +--------------------+ 
  26. | information_schema | 
  27. | demo | 
  28. | mysql | 
  29. | performance_schema | 
  30. +--------------------+ 
  31. rows in set (0.00 sec) 
  32. ​ 
  33. mysql> use demo; 
  34. Reading table information for completion of table and column names 
  35. You can turn off this feature to get a quicker startup with -A 
  36. ​ 
  37. Database changed 
  38. mysql> show tables; 
  39. +--------------------+ 
  40. | Tables_in_demo | 
  41. +--------------------+ 
  42. | demo_users | 
  43. | hibernate_sequence | 
  44. +--------------------+ 
  45. rows in set (0.00 sec) 
  46. ​ 
  47. mysql> select * from demo_users; 
  48. +----+---------------------+---------------------+-------------+------+------+ 
  49. | id | birth_day | create_date | email | name | sex | 
  50. +----+---------------------+---------------------+-------------+------+------+ 
  51. | 1 | 2019-03-31 04:03:43 | 2019-03-31 04:03:43 | A1@test.com | A1 | 0 | 
  52. | 2 | 2019-03-31 04:03:43 | 2019-03-31 04:03:43 | B2@test.com | B2 | 1 | 
  53. +----+---------------------+---------------------+-------------+------+------+ 
  54. rows in set (0.00 sec) 

通过mysql命令行我们可以看到刚才的测试数据已经保存到数据库中。


本文转载自网络,原文链接:https://www.toutiao.com/a6756397345098695176/
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐