一. YAML文件格式说明
YAML 是一种简洁的非标记语言。
语法格式:
• 缩进表示层级关系
• 不支持制表符“tab”缩进,使用空格缩进
• 通常开头缩进 2 个空格
• 字符后缩进 1 个空格,如冒号、逗号等
• “---” 表示YAML格式,一个文件的开始
• “#”注释
二. YAML文件创建资源对象
https://kubernetes.io/docs/concepts/workloads/controllers/deployment/
1. YAML配置文件结构
yaml结构.png2. 创建deployment控制器及pod
创建一个nginx-deployment控制器,运行三个pod
# cat nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.15.4
ports:
- containerPort: 80
# kubectl create -f nginx-deployment.yaml
# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-deployment-d55b94fd-7ngvd 1/1 Running 0 2m36s
nginx-deployment-d55b94fd-x99bf 1/1 Running 0 2m36s
nginx-deployment-d55b94fd-ztwq5 1/1 Running 0 2m36s
3. 创建service发布端口
创建一个nginx-service service发布端口:
# cat nginx-service.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
labels:
app: nginx
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
selector:
app: nginx
# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.0.0.1 <none> 443/TCP 3d23h
nginx-service NodePort 10.0.0.31 <none> 80:39694/TCP 6s
浏览器访问http://10.40.6.210:39694/ 任意一个node节点IP加上暴露端口即可访问
其实可以将调度器和service 放到同一个yaml文件,用“---”隔开,完成一个应用的创建和发布
# cat nginx-deployment_service.yaml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.15.4
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
labels:
app: nginx
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
selector:
app: nginx
# kubectl create -f nginx-deployment_service.yaml
deployment.apps/nginx-deployment created
service/nginx-service created
三. 如何记住yaml配置文件字段
• 用run命令生成,--dry-run 测试命令是否成功,不会创建资源, 然后将不要的字段删除或调整相应字段值
# kubectl run --image=nginx my-deploy -o yaml --dry-run
# kubectl run nginx --image=nginx:1.15.4 --port=80 --replicas=3 --dry-run -o yaml > my-deploy.yaml
• 用get命令导出现有资源的yaml配置文件:
kubectl get deploy/nginx-deployment --export -o yaml > my-deploy.yaml
• Pod容器的字段拼写忘记了,查看字段说明及使用
kubectl explain pods.spec.containers
网友评论