在 Kubernetes 中,能够快速生成各种 YAML 配置文件是一项非常重要的技能。下面介绍 4 种方法:

1. 使用 kubectl 命令行生成标准的 Deployment 和 Service 配置

我们可以使用 kubectl create 命令创建一个 Nginx Deployment,并加上 --dry-run -o yaml 参数来快速生成 YAML 配置:

kubectl create deployment nginx--image=nginx --dry-run -o yaml
  • 1.

这将输出一个标准的 Nginx Deployment YAML 配置。

接下来我们可以基于上面的 Deployment 生成对应的 Service YAML 配置:

kubectl expose deployment nginx--port=80 --target-port=80 --dry-run -o yaml
  • 1.

2. 利用 Helm 查看官方标准的复杂 YAML 配置

Helm 是 Kubernetes 的包管理工具,它提供了大量的官方 Chart,我们可以利用这些 Chart 查看复杂应用的 YAML 配置:

# 添加 Aliyun 的 Chart 仓库
helm repo add aliyun-apphub https://apphub.aliyuncs.com
helm repo update

# 安装 RabbitMQ 集群并查看 YAML 配置
helm install -n rq rabbitmq-ha aliyun-apphub/rabbitmq-ha --dry-run --debug
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

3. 使用 Kompose 将 Docker Compose 转换为 Kubernetes YAML 配置

Kompose 是一个开源工具,可以将 Docker Compose 文件转换为 Kubernetes 的 YAML 配置:

# 下载 Kompose 二进制包
wget https://github.com/kubernetes/kompose/releases/download/v1.22.0/kompose-linux-amd64

# 转换 Docker Compose 配置
./kompose-linux-amd64 -f docker-compose.yml convert
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

4. 手动将 Docker 命令转换为 Kubernetes YAML 配置

有时我们需要手动将 Docker 命令转换为 Kubernetes 的 YAML 配置。以 Prometheus Node Exporter 为例:

Docker 运行命令:

docker run -d \
    -v "/proc:/host/proc" \
    -v "/sys:/host/sys" \  
    -v "/:/rootfs" \
    --net=host \  
    prom/node-exporter \  
    --path.procfs /host/proc \  
    --path.sysfs /host/sys \  
    --collector.filesystem.ignored-mount-points "^/(sys|proc|dev|host|etc)($|/)"
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

转换为 Kubernetes DaemonSet YAML 配置 node_exporter.yml:

apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: node-exporter-daemonset
spec:
  template:
    metadata:
      labels:
        app: prometheus
    spec:
      hostNetwork: true
      containers:
      - name: node-exporter
        image: prom/node-exporter
        imagePullPolicy: IfNotPresent
        command:
        - /bin/node_exporter
        - --path.procfs
        - /host/proc
        - --path.sysfs
        - /host/sys
        - --collector.filesystem.ignored-mount-points
        - ^/(sys|proc|dev|host|etc)($|/)
        volumeMounts:
        - name: proc
          mountPath: /host/proc
        - name: sys
          mountPath: /host/sys
        - name: root
          mountPath: /rootfs
      volumes:
      - name: proc
        hostPath:
          path: /proc
      - name: sys
        hostPath:
          path: /sys
      - name: root
        hostPath:
          path: /
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.

总结起来,这四种方法可以帮助我们快速生成各种 Kubernetes YAML 配置,提高工作效率。