系统学习 DevOps 学习路径:从版本控制到可观测与供应链

cdk8s

cdk8s Kubernetes 清单生成

补充说明

cdk8s 用 TypeScript、Python、Java 等语言定义 Kubernetes 清单,编译成 YAML。适合需要复用逻辑、类型检查和编程抽象的团队。

核心概念:App、Chart、ApiObject、Construct。

常用示例

初始化项目:

npm install -g cdk8s-cli
cdk8s init typescript-app

定义 Chart:

import { App, Chart, ChartProps } from 'cdk8s';
import { Deployment, Service } from './imports/k8s';

export class MyChart extends Chart {
  constructor(scope: App, id: string, props?: ChartProps) {
    super(scope, id, props);
    const app = new Deployment(this, 'app', {
      spec: {
        replicas: 2,
        selector: { matchLabels: { app: 'demo' } },
        template: {
          metadata: { labels: { app: 'demo' } },
          spec: { containers: [{ name: 'app', image: 'nginx:1.30' }] },
        },
      },
    });
    new Service(this, 'svc', {
      spec: { selector: { app: 'demo' }, ports: [{ port: 80 }] },
    });
  }
}

const app = new App();
new MyChart(app, 'demo');
app.synth();

生成并应用:

cdk8s synth
kubectl apply -f dist/

易错点与排错

相关命令

参考链接

读完自测

合上页面,先回答,再展开对照。

  1. 运行 cdk8s synth 后 dist/ 为空,可能是什么原因?
  2. 修改 Chart 名称会带来什么影响?
  3. 生成的 YAML 能直接 kubectl apply 吗?为什么?
答案
  1. 很可能没有调用 app.synth();不调用就不会生成清单。
  2. Chart 名称变化会导致资源名变化,从而触发资源重建。
  3. 不建议直接 apply;生成的 YAML 应先经过策略检查,避免带入风险。
微信小程序码:扫码打开命令速查小程序

小程序版

微信扫码,随时查命令