示例:實現 運行在 Tomcat裏的 Web app,JSP頁面經過 JDBC 直接訪問 MySQL數據庫並展現數據。node
需求:Web App 容器 MySQL容器,web--->mysqlmysql
須要把MySQL容器的IP地址經過環境變量的方式注入 Web App容器裏,同時,須要將Web App容器的 8080端口映射宿主機的 8080端口,以便在外部訪問。web
1.YAML編寫sql
1.MySQL服務建立一個 RC 文件數據庫
# cat mysql-rc.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: mysql
spec:
replicas: 1
selector:
matchLabels:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql:5.7
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "123456"
api
# kubectl create -f mysql-rc.yaml replicationcontroller/mysql created
查看咱們建立的podtomcat
# kubectl get pods | grep mysql mysql-76999dd7c8-cgcwk 1/1 Running 0 40m
1.2 MySQL服務建立一個 SVC 文件bash
# cat mysql-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
selector:
app: mysql
app
# kubectl create -f mysql-svc.yaml service/mysql created
# kubectl get svc | grep mysql mysql ClusterIP 10.0.0.127 <none> 3306/TCP 42m
MySQL服務分配了 10.0.0.127 的Cluster IP地址,這是一個虛擬IP地址,隨後,Kubernetes集羣中中的其餘新建立的 Pod就能夠經過 Service 的 Cluster IP+端口號 6379來鏈接和訪問它。ide
根據 Service 的惟一名字,容器能夠從環境變量中獲取到 Service對應的 Cluster IP地址和端口,從而發起 TCP/IP 鏈接請求。
1.3 Tomcat 服務建立一個 RC 文件
# cat myweb-rc.yaml
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: myweb
spec:
replicas: 2
selector:
matchLabels:
app: myweb
template:
metadata:
labels:
app: myweb
spec:
containers:
- name: myweb
image: kubeguide/tomcat-app:v1
ports:
- containerPort: 8080
env:
- name: MYSQL_SERVICE_HOST
#value: 'mysql' #備註,此處沒有域名解析,最好配置MySQL集羣地址
value: '10.0.0.127' # kubectl get svc可得
- name: MYSQL_SERVICE_PORT
value: '3306'
# kubectl create -f myweb-rc.yaml replicationcontroller/myweb created
# kubectl get pods | grep myweb myweb-77b4646d58-tcmds 1/1 Running 0 19m myweb-77b4646d58-wkzx6 1/1 Running 0 19m
1.4 Tomcat 服務建立一個 SVC 文件
# cat myweb-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myweb
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30001
selector:
app: myweb
# kubectl create -f myweb-svc.yaml service/myweb created
# kubectl get svc | grep myweb myweb NodePort 10.0.0.27 <none> 8080:30001/TCP 44m
2.進行驗證
# kubectl get pods -o wide | grep myweb NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES myweb-77b4646d58-tcmds 1/1 Running 0 22m 172.17.30.6 192.168.200.129 <none> <none> myweb-77b4646d58-wkzx6 1/1 Running 0 22m 172.17.39.6 192.168.200.130 <none> <none>
http://192.168.200.130:30001/demo
提交成功
經過MySQL容器進行驗證查詢
表示部署OK!