创建 Pod
学习目标
- 掌握使用 kubectl 创建 Pod 的方法
- 理解命令式和声明式创建的区别
- 能够验证 Pod 创建成功
核心概念
两种创建方式
命令式(命令行直接创建):
kubectl run nginx --image=nginx
声明式(通过 YAML 文件创建):
kubectl apply -f pod.yaml
推荐:声明式(可版本控制、可重复)
命令式创建
# 基本创建
kubectl run nginx --image=nginx
# 指定端口
kubectl run nginx --image=nginx --port=80
# 指定标签
kubectl run nginx --image=nginx --labels=app=web,env=prod
# 指定命名空间
kubectl run nginx --image=nginx --namespace=dev
# 指定环境变量
kubectl run nginx --image=nginx --env="ENV=production"
| 参数 | 说明 |
|---|---|
--image | 容器镜像 |
--port | 容器端口 |
--labels | 标签 |
--namespace | 命名空间 |
--env | 环境变量 |
--dry-run=client | 只生成 YAML 不创建 |
声明式创建
# 步骤 1: 编写 YAML
vim pod.yaml
# 步骤 2: 应用配置
kubectl apply -f pod.yaml
# 步骤 3: 验证创建
kubectl get pod nginx
从命令生成 YAML
# 生成 YAML 但不创建
kubectl run nginx --image=nginx --dry-run=client -o yaml > pod.yaml
# 查看生成的 YAML
cat pod.yaml
# 修改后应用
kubectl apply -f pod.yaml
创建流程详解
kubectl apply -f pod.yaml
↓
API Server
↓
验证配置
↓
存储到 etcd
↓
Scheduler 调度
↓
分配到 Node
↓
Kubelet 拉取镜像
↓
启动容器
↓
Pod Running
验证 Pod 创建
# 查看 Pod 状态
kubectl get pod nginx
# 查看详细信息
kubectl describe pod nginx
# 查看 Pod 日志
kubectl logs nginx
# 查看 Pod IP
kubectl get pod nginx -o wide
创建示例
示例 1: 简单 Web 服务
# web-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: web
labels:
app: web
spec:
containers:
- name: nginx
image: nginx:1.24
ports:
- containerPort: 80
kubectl apply -f web-pod.yaml
kubectl get pod web
示例 2: 带配置的应用
# app-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: app
labels:
app: backend
spec:
containers:
- name: app
image: my-app:1.0
ports:
- containerPort: 8080
env:
- name: DB_HOST
value: "mysql"
- name: DB_PORT
value: "3306"
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
kubectl apply -f app-pod.yaml
kubectl get pod app
创建失败排查
# 查看 Pod 状态
kubectl get pod nginx
# 查看事件
kubectl describe pod nginx | grep -A 10 Events
# 常见状态
Pending: 调度中或资源不足
ImagePullBackOff: 镜像拉取失败
CrashLoopBackOff: 容器反复崩溃
创建多容器 Pod
# multi-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: multi
spec:
containers:
- name: web
image: nginx
ports:
- containerPort: 80
- name: sidecar
image: busybox
command: ['sh', '-c', 'while true; do echo hello; sleep 10; done']
kubectl apply -f multi-pod.yaml
kubectl get pod multi
实践练习
练习 1: 命令式创建
使用命令创建一个 nginx Pod:
kubectl run my-nginx --image=nginx --port=80
练习 2: 声明式创建
编写 YAML 创建一个 Pod:
- 名称:my-app
- 镜像:httpd:latest
- 端口:80
- 标签:app=web
练习 3: 生成 YAML
使用 --dry-run 生成 YAML:
kubectl run my-pod --image=nginx --dry-run=client -o yaml > pod.yaml
练习 4: 创建多容器 Pod
创建一个包含 nginx 和 redis 的 Pod。
常见误解
1. kubectl run 的行为
错误:kubectl run 创建 Deployment
正确:
- K8s 1.18+: kubectl run 创建 Pod
- K8s 1.17-: kubectl run 创建 Deployment
版本不同行为不同,注意检查
2. apply vs create
create: 创建资源(已存在会报错)
apply: 创建或更新资源(幂等操作)
推荐使用 apply
小结
| 要点 | 说明 |
|---|---|
| 命令式 | kubectl run 快速创建 |
| 声明式 | YAML + kubectl apply |
| 推荐 | 声明式(可版本控制) |
| 验证 | get / describe / logs |
| 排错 | 查看 Events 和状态 |
| 幂等 | apply 可重复执行 |
练习编辑器
bash
Loading...