这个章节展示了如何使用Kubernetes Deployment对象运行一个应用程序。
创建一个nginx deployment
可以用Kubernetes Deployment对象创建一个应用程序,并且可以用YAML文件来描述Deployment。下面这个YAML文件描述了一个Deployment运行了一个nginx:1.7.9镜像。
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2 # tells deployment to run 2 pods matching the template
template: # create pods using pod definition in this template
metadata:
# unlike pod-nginx.yaml, the name is not included in the meta data as a unique name is
# generated from the deployment name
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
1.基于YAML文件创建一个Deployment:
kubectl create -f nginx.yaml
2.显示这个Deployment详细信息:
kubectl describe deployment nginx-deployment
user@computer:~/kubernetes.github.io$ kubectl describe deployment nginx-deployment
Name: nginx-deployment
Namespace: default
CreationTimestamp: Tue, 30 Aug 2016 18:11:37 -0700
Labels: app=nginx
Selector: app=nginx
Replicas: 2 updated | 2 total | 2 available | 0 unavailable
StrategyType: RollingUpdate
MinReadySeconds: 0
RollingUpdateStrategy: 1 max unavailable, 1 max surge
Conditions:
Type Status Reason
---- ------ ------
Available True MinimumReplicasAvailable
OldReplicaSets:
NewReplicaSet: nginx-deployment-1771418926 (2/2 replicas created)
No events.
3.查看创建的deployment列表:
kubectl get pods -l app=nginx
NAME READY STATUS RESTARTS AGE
nginx-deployment-1771418926-7o5ns 1/1 Running 0 16h
nginx-deployment-1771418926-r18az 1/1 Running 0 16h
4.显示pod的详细信息:
kubectl describe pod
更新deployment
可以用一个新的YAML文件更新deployment。这个YAML文件指定了deployment把镜像更新成nginx 1.8。
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.8 # Update the version of nginx from 1.7.9 to 1.8
ports:
- containerPort: 80
1.更新deployment
kubectl apply -f nginx.yaml
2.观察这个deployment创建了一个新的pod并且把老的删除:
kubectl get pods -l app=nginx
扩缩应用程序副本数量
可以使用一个新的YAML文件增加deployment里面pod的数量。这个YAML文件设置replicas为4,指定的Deployment将有4个pod:
apiVersion: apps/v1beta1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 4 # Update the replicas from 2 to 4
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.8
ports:
- containerPort: 80
1.应用新的YAML文件:
kubectl apply -f nginx.yaml
2.验证这个Deployment是否包含4个pod:
kubectl get pods -l app=nginx
输出类似于下面:
NAME READY STATUS RESTARTS AGE
nginx-deployment-148880595-4zdqq 1/1 Running 0 25s
nginx-deployment-148880595-6zgi1 1/1 Running 0 25s
nginx-deployment-148880595-fxcez 1/1 Running 0 2m
nginx-deployment-148880595-rwovn 1/1 Running 0 2m
删除Deployment
根据名字删除deployment:
kubectl delete deployment nginx-deployment
ReplicationControllers-上一代方法
创建包含多个副本的应用程序优先使用Deployment,反过来又使用ReplicaSet。在Deployment和ReplicaSet添加到Kubernetes里面之前是使用ReplicationController创建应用。