转自:https://blog.51cto.com/forall/2048671
Replication Controller简称RC,它能够保证Pod持续运行,并且在任何时候都有指定数量的Pod副本,在此基础上提供一些高级特性,比如滚动升级和弹性伸缩
它在k8s中的架构如图:
RC会在每个节点上创建Pod,Pod上如果有相应的Images可以直接创建,如果没有,则会拉取这个镜像再进行创建
一.下面直接来看下在RC中的常见操作:
1.编辑配置文件
vim rc.json
{
"apiVersion": "v1",
"kind": "ReplicationController",
"metadata": { #设置rc的元数据
"name": "nginx-rc"
},
"spec": { #设置rc的具体规格
"replicas": 2, #设置Pod的具体数量
"selector": { #通过selector来匹配相应的Pod的label
"name": "myservice"
},
"template": { #设置Pod的模板
"metadata": {
"labels": {
"name":"myservice"
}
},
"spec": {
"containers": [{
"name": "nginx",
"image": "nginx",
"imagePullPolicy": "IfNotPresent", #镜像拉取策略,分为Always,Never,IfNotPresent,默认是Always
"ports": [{
"containerPort": 80
}]
}]
}
}
}
}
2.创建RC
kubectl create -f rep.json
replicationcontroller "nginx-rc" created
3.查询rc
kubectl get rc nginx-rc
要求有2个,已经成功创建的也是两个
4.查询pod运行情况
kubectl get pod -l name #-l 指定selector的key
可以看到两个创建好的pod,已经在Running状态
5.当删除其中一个Pod或者删除全部Pod的时候,RC会自动再次创建Pod,直到满足配置文件中定义的个数
kubectl delete pod nginx-rc-lbb7m
pod "nginx-rc-lbb7m" deleted
kubectl get pod -l name
二.弹性伸缩
弹性伸缩就是在现有环境不能满足业务需求的时候,进行的扩容或缩容
1.缩容Pod
kubectl scale replicationcontroller nginx-rc --replicas=1
replicationcontroller "nginx-rc" scaled
kubectl get pod -l name
kubectl get rc nginx-rc
2.扩容Pod
kubectl scale replicationcontroller nginx-rc --replicas=3
replicationcontroller "nginx-rc" scaled
kubectl get pod -l name
kubectl get rc nginx-rc
3.判断当前Pod副本是否正确,并修改数量
kubectl scale rc nginx-rc --current-replicas=3 --replicas=1
判断当前副本数是否为3个,如果是,则更改为1个副本
三.滚动升级
在滚动升级/更新方面,有一种更简单的机制,Depolyment
1.创建Depolyment
vim nginx-deployment.yaml #配置文件基本一致,就是改个类型,这里就不赘述了
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
imagePullPolicy: Never
ports:
- containerPort: 80
hostPort: 8181
2.带记录点的方式创建Depolyment,在这条命令下面将开始记录所有对Depolyment的操作
kubectl create -f nginx-deployment.yaml --record
3.查询创建的Depolyment
kubectl get deployment
4.查询当前所在的记录点
kubectl rollout history deployment nginx-deployment
5.升级/更新这个Depolyment
vim nginx-deployment.yaml
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginxv2 #更换源Images
imagePullPolicy: Never
ports:
- containerPort: 80
hostPort: 8181
kubectl apply -f nginx-deployment.yaml
deployment "nginx-deployment" configured
6.如果发现更改错误,可以进行回滚操作
kubectl rollout undo deployment nginx-deployment --to-revision=1 #回到编号为1的操作
deployment "nginx-deployment" rolled back
7.删除Depolyment
kubectl delete -f nginx-deployment.yaml