前提准备:
安装好Docker和Kubernetes,初学者的话可以部署单节点集群,即Docker for Mac/Windows,上一篇文章我已经写过如何搭建单节点集群。如果是多节点集群调度,则可以参考这篇文章。
部署前提:
先编写一个springboot的一个demo,没接触过springboot的同学可以参考这篇文章。我这边对springboot的demo做了小小的改动,我是和springboot自身的springboot JPA进行搭建的,没用mybatis或者hibernate进行整合。

还有一个小小的改动是springboot中配置数据库时,是在application.properties文件中先配置成功。然后在进行连接,这一点我觉得扩展性不太好,就手动写个方法去替换文件中数据库配置的参数,以满足通过配置参数连接更多类型的数据库。

我的demo里,template部分采用angular1.0进行编写的,当时是为了学习angular然后嵌套进去的。

开始部署:
先编写mysql的mysql-deploy.yaml脚本,然后执行
kubectl apply -f mysql-deployment.yaml
即可启动mysql容器:

接下来编写mysql-service.yaml脚本,然后执行
kubectl apply -f mysql-service.yaml
即可启动mysql的Service服务:

由于我才用的是NodePort方式,所以本地可视化工具也可以进行连接,端口使用的是对外暴露的nodePort,如果采用ClusterIP,则需要开启proxy,例如:
kubectl proxy --port=8888
下图是采用NodePort方式启动的:

接下来编写myweb-deploy.yaml,注意一点的是现在我们采用容器间相互通讯,所有的网络通讯是在docker所划分的整个网络中,故mysql数据库的地址也必须是docker网络子网中给mysql分配的一个有效IP地址,可以通过查看mysql这个pod的详情进行查看所属IP,命令如下:
kubectl describe pod mysql-d7d8c74cc-f7rc4
即可看到IP为10.1.0.62,所以myweb-deploy.yaml脚本中,数据库的地址必须配置为刚才获取到的IP地址,而不是本地的IP或者采用localhost,很多新手在这里容易搞混。

myweb这个pod是容器网络中,总docker的子网中一个有效的IP地址,然后执行
kubectl apply -f web-deployment.yaml
即可创建web服务的pod

接下来创建myweb-service.yaml,然后执行
kubectl apply -f myweb-service.yaml
即可创建好myweb的Service服务

接下来查看myweb的日志

接下来我们查看本机的pod和svc

发现pod和service都处于running状态,然后通过nodeIP:nodePort的方式调用服务的接口

由于我采用单节点方式部署,容器之外的nodeIP可以是localhost,也可以通过ipconfig查看本机所属网络的具体IP地址,

通过本地所属网络IP,即也属于nodeIP:nodePort方式,访问url后,页面如下

这部分springboot的代码以托管到GitHub上,地址如下:k8s-docker-springboot
网友评论