这个示例是《Kubernetes 权威指南(第二版)》第一章中的例子,部署一个 Java 应用,访问 MySql 数据库。
需要启动2个容器,webapp 和 mysql,每个容器各需要2个配置文件(ReplicationController + Service)。
MySql 的配置文件
mysql-rc.yaml
apiVersion: v1
kind: ReplicationController # kind 指明此资源对象的类型
metadata:
name: mysql # 元数据 - 此资源对象的名称,全局唯一
spec:
replicas: 1 # Pod 副本期待的数量
selector:
app: mysql # label 标签,选择有此 label 的 Pod
template: # 定义创建 Pod 实例的模板
metadata:
labels:
app: mysql # Pod 的 label,对应上面 rc 的 selector
spec:
containers: # 定义 Pod 中的容器
- name: mysql # 容器名称
image: mysql:5.6 # 使用的 docker image
ports:
- containerPort: 3306 # 容器暴露的端口号
env: # 注入到容器内的环境变量
- name: MYSQL_ROOT_PASSWORD
value: '123456'
mysql-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
type: NodePort
ports:
- port: 3306
selector:
app: mysql
web app 配置文件
myweb-rc.yaml
apiVersion: v1
kind: ReplicationController
metadata:
name: myweb
spec:
replicas: 1
selector:
app: myweb
template:
metadata:
labels:
app: myweb
spec:
containers:
- name: myweb
image: kubeguide/tomcat-app:v1
ports:
- containerPort: 8080
env:
- name: GET_HOSTS_FROM
value: dns
- name: MYSQL_SERVICE_HOST
value: 'mysql'
- name: MYSQL_SERVICE_PORT
value: '3306'
myweb-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myweb
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30001
selector:
app: myweb
启动
kubectl apply -f mysql-rc.yaml
kubectl apply -f mysql-svc.yaml
kubectl apply -f myweb-rc.yaml
kubectl apply -f myweb-svc.yaml
查看pods :
kubectl get pods
NAME READY STATUS RESTARTS AGE
mysql-r5vn7 1/1 Running 1 2d14h
myweb-8nm2m 1/1 Running 1 2d14h
查看service:
kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.152.183.1 <none> 443/TCP 8d
mysql NodePort 10.152.183.70 <none> 3306:30361/TCP 2d14h
myweb NodePort 10.152.183.52 <none> 8080:30001/TCP 2d14h
访问
myweb 服务对外的端口是 30001,访问 http://<IP>:30001/demo/
kubenetes实现tomcat+mysql快速部署
访问kubenetes的demo
# http://ip/30001/demo/
# vim mysql-rc.yaml
apiVersion: v1
kind: ReplicationController
metadata:
name: mysql
spec:
replicas: 1
selector:
app: mysql
template:
metadata:
labels:
app: mysql
spec:
containers:
- name: mysql
image: mysql
ports:
- containerPort: 3306
env:
- name: MYSQL_ROOT_PASSWORD
value: "password"
# vim mysql-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: mysql
spec:
ports:
- port: 3306
selector:
app: mysql
# vim myweb-rc.yaml
apiVersion: v1
nd: ReplicationController
metadata:
name: myweb
spec:
replicas: 1
selector:
app: myweb
template:
metadata:
labels:
app: myweb
spec:
containers:
- name: myweb
image: kubeguide/tomcat-app:v1
ports:
- containerPort: 8080
# vim myweb-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: myweb
spec:
type: NodePort
ports:
- port: 8080
nodePort: 30001
selector:
app: myweb