kubectl create
通过命令行快速创建资源(命令式)
语法
kubectl create <resource> <name> [flags]
参数
| 参数 | 说明 | 示例 | 级别 |
|---|---|---|---|
--image |
指定容器镜像 | kubectl create deployment nginx --image=nginx:1.25 |
常用 |
--replicas |
指定副本数 | kubectl create deployment web --image=nginx --replicas=3 |
常用 |
--dry-run=client |
模拟创建并输出 YAML | kubectl create deployment web --image=nginx --dry-run=client -o yaml |
常用 |
--from-literal |
从字面值创建 ConfigMap/Secret | kubectl create configmap app-config --from-literal=key=value |
常用 |
--from-file |
从文件创建 ConfigMap/Secret | kubectl create configmap app-config --from-file=config.yaml |
常用 |
示例
创建 Deployment
kubectl create deployment nginx --image=nginx:1.25 --replicas=3
快速创建一个 3 副本的 Nginx 部署
生成 YAML 模板
kubectl create deployment web --image=nginx --dry-run=client -o yaml > deployment.yaml
用 create 生成 YAML 再用 apply 管理
创建 ConfigMap
kubectl create configmap db-config --from-literal=DB_HOST=mysql --from-literal=DB_PORT=3306
从键值对创建配置
创建 Secret
kubectl create secret generic db-secret --from-literal=password=mypassword
值会自动 Base64 编码
创建命名空间
kubectl create namespace staging
创建新的命名空间隔离环境
常见错误
already exists
资源已存在,用 kubectl apply 更新或先删除再创建
invalid image name
检查镜像名称格式,确认镜像仓库可访问
技巧
- create 是命令式操作,生产环境推荐用 apply + YAML 文件管理
- 用 --dry-run=client -o yaml 快速生成 YAML 模板非常实用
- create 不支持更新,重复执行会报错