《深入剖析Kubernetes - 12 牛刀小试:我的第一个容器化应用》
主要包括2个步骤:制作镜像 和 编写yaml配置文件(或json)
以 nginx 的deployment 为例
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 2
template:
metadata: labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.7.9
ports:
- containerPort: 80
其中kind 字段声明类型,例如deployment、daemonset 等,metadata 是具体描述,例如name、namespace、labels、annotations等
spec.template 描述了pod 的细节,即容器配置的模板
创建deployment
$ kubectl create -f nginx-deployment.yaml
查看deployment运行情况
$ kubectl get pods -l app=nginx
NAME READY STATUS RESTARTS AGE n
ginx-deployment-67594d6bf6-9gdvr 1/1 Running 0 10m
nginx-deployment-67594d6bf6-v6j7w 1/1 Running 0 10m
查看API 对象细节
kubectl describe pod nginx-deployment-67594d6bf6-9gdvr
Name: nginx-deployment-67594d6bf6-9gdvr
Namespace: default
Priority: 0
PriorityClassName: <none>
Node: node-1/10.168.0.3
Start Time: Thu, 16 Aug 2018 08:48:42 +0000
Labels: app=nginx
pod-template-hash=2315082692
Annotations: <none>
Status: Running
IP: 10.32.0.23
Controlled By: ReplicaSet/nginx-deployment-67594d6bf6
...
Events:
Type Reason Age From Message
---- ------ ---- ---- -------
Normal Scheduled 1m default-scheduler Successfully assigned default/nginx-deployment-67594d6bf6-9gdvr to node-1
Normal Pulling 25s kubelet, node-1 pulling image "nginx:1.7.9"
Normal Pulled 17s kubelet, node-1 Successfully pulled image "nginx:1.7.9"
Normal Created 17s kubelet, node-1 Created container
Normal Started 17s kubelet, node-1 Started container
其中Events 字段可用于后期问题定位,常见的有
(1)找不到合适的node节点调度pod,包括
node节点label匹配不上;
node节点资源不够分配;
node节点设置了污点;
node节点网络异常;
(2) 镜像拉取失败
升级容器镜像版本
...
spec:
containers:
- name: nginx
image: nginx:1.8 # 这里被从 1.7.9 修改为 1.8
ports:
- containerPort: 80
执行
$ kubectl replace -f nginx-deployment.yaml
更常见的方式是,通过apply 执行相关操作,无论是创建还是修改都可以通过该命令完成
$ kubectl apply -f nginx-deployment.yaml
# 修改 nginx-deployment.yaml 的内容
$ kubectl apply -f nginx-deployment.yaml
下面是一个volume挂载的例子
通常分为emptyDir 和 hostPath 两种,两者的区别在于前者不需要指定宿主机目录(源目录),k8s 会在宿主机上创建一个临时目录并挂载进去;而后者,则需要显式声明挂载的源目录,例如将宿主机的/usr/local/nginx/html 目录挂载到容器同样的位置
emptyDir的例子
volumes:
- name: nginx-vol
emptyDir: {}
hostPath的例子
...
volumes:
- name: nginx-vol
hostPath:
path: /var/data
进入容器
$ kubectl exec -it nginx-deployment-5c678cfb6d-lg9lw -- /bin/bash
# ls /usr/share/nginx/html
删除容器
$ kubectl delete -f nginx-deployment.yaml