第四章 Kubernetes進階之yaml配置文件


  YAML是一種簡潔的非標記語言

  百度百科:https://baike.baidu.com/item/YAML/1067697?fr=aladdin

  語法格式

  • 縮進表示層級關系
  • 不支持制表符tab縮進,使用空格縮進
  • 通常開頭縮進2個空格
  • 字符后縮進1個空格,如冒號,逗號等
  • "--"表示YAML格式,一個文件的開始
  • "#"注釋

  yaml文件示例nginx-deployment.yaml

apiVersion: apps/v1 #apiVersion是當前配置格式的版本
kind: Deployment #kind是要創建的資源類型,這里是Deploymnet
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec: #spec部分是該Deployment的規則說明
  replicas: 3 #relicas指定副本數量,默認為1
  selector:
    matchLabels:
      app: nginx
  template: #template定義Pod的模板,這是配置的重要部分
    metadata: #metadata定義Pod的元數據,至少要頂一個label,label的key和value可以任意指定
      labels:
        app: nginx
    spec: #spec描述的是Pod的規則,此部分定義pod中每一個容器的屬性,name和image是必需的
      containers:
      - name: nginx
        image: nginx:1.15.4
        ports:
        - containerPort: 80

   PS:注釋#需要間隔一個空格不能間隔多個空格或者tab 否則啟動會出現以下報錯

# kubectl create -f nginx-deployment.yaml 
error: error parsing nginx-deployment.yaml: error converting YAML to JSON: yaml: line 8: could not find expected ':'

   通過yaml文件創建deployment

kubectl create -f nginx-deployment.yaml

   通過yaml文件創建service

# cat nginx-service.yaml 
apiVersion: v1
kind: Service #創建類型是service
metadata:
  creationTimestamp: null
  labels:
    app: nginx
  name: nginx-service
spec:
  ports:
  - port: 80
    protocol: TCP
    targetPort: 80
  selector:
    app: nginx
  type: NodePort

   創建

kubectl create -f nginx-service.yaml 

   查看,對外暴露43208端口

# kubectl get svc
NAME            TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP   10.10.10.1     <none>        443/TCP        4d23h
nginx-service   NodePort    10.10.10.168   <none>        80:43208/TCP   17s

   訪問

 

   可以通過以下命令不運行而生成yaml文件

kubectl expose deployment nginx-deployment --port=80 --type=NodePort --target-port=80 --name=nginx-service --dry-run -o yaml

   使用yaml文件創建應用與kucectl直接創建應用的不同之處是便於留存,而且可以把剛剛兩個配置文件放在一起進行配置

   使用命令生成yaml配置文件

kubectl run nginx --image=nginx:latest --port=80 --replicas=3 --dry-run -o yaml
# --dry-run 測試不運行
#-o yaml 輸出為yaml格式

   生成的yaml文件重定向輸出至文件

kubectl run nginx --image=nginx:latest --port=80 --replicas=3 --dry-run -o yaml >my-deploy.yaml

 

# cat my-deploy.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    run: nginx
  name: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      run: nginx
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        run: nginx
    spec:
      containers:
      - image: nginx:latest
        name: nginx
        ports:
        - containerPort: 80
        resources: {}
status: {}

   對於已經在運行的的可以使用get命令導出

kubectl get deploy/nginx --export -o yaml > my-deploy2.yaml

   Pod容器字段忘記拼寫了可以通過以下命令查看

kubectl explain pods.spec.containers

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM