创建普通测试Pod
主要用于验证应用本身的功能或测试无状态服务,其生命周期短暂,不关心数据存储。
其基本流程是:编写Pod定义文件 -> 部署Pod -> 验证功能 -> 清理资源。
编写Pod定义文件:
# test-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: simple-test-pod
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
创建Pod
kubectl apply -f test-pod.yaml
验证状态
kubectl get pods -o wide
测试访问(可能需端口转发)
kubectl port-forward simple-test-pod 8080:80
清理
kubectl delete -f test-pod.yaml
使用PVC进行测试的流程
使用PVC测试侧重于验证存储的持久化能力。整个过程涉及PV(提供存储资源)和PVC(申请存储资源)的交互。
其基本流程是:准备存储后端 -> 定义PV/PVC -> 在Pod中挂载PVC -> 验证数据持久性。以下是关键步骤:
-
准备存储 :确保有一个可用的存储后端。在您的环境里,Longhorn 已经创建了一个名为
longhorn的StorageClass,它会动态地为您准备PV,无需手动创建。 -
定义并申请存储(PVC):您只需要创建一个PVC,指定需要多大的空间和访问模式。Longhorn会自动满足这个申请。
test-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-test-pvc
spec:
storageClassName: longhorn # 指定使用Longhorn提供的存储
accessModes:
- ReadWriteOnce # 常见的访问模式,表示可被单个节点以读写方式挂载
resources:
requests:
storage: 1Gi # 申请1GB的存储空间
创建PVC
kubectl apply -f test-pvc.yaml
查看PVC状态,应为Bound,表示已成功绑定由Longhorn自动创建的PV
kubectl get pvc my-test-pvc
3.在Pod中使用PVC:在Pod的定义中声明使用这个PVC。
# pod-with-pvc.yaml
apiVersion: v1
kind: Pod
metadata:
name: pod-using-pvc
spec:
containers:
- name: app
image: nginx:latest
volumeMounts:
- mountPath: "/data" # 容器内的挂载路径
name: storage-volume
volumes:
- name: storage-volume
persistentVolumeClaim:
claimName: my-test-pvc # 引用上面创建的PVC
创建Pod
kubectl apply -f pod-with-pvc.yaml
4.验证数据持久性:这是测试的核心。
# 进入Pod,写入测试数据
kubectl exec -it pod-using-pvc -- sh -c "echo 'Hello, Persistent World!' > /data/testfile.txt"
# 删除这个Pod
kubectl delete pod pod-using-pvc
# 用同样的yaml文件重新创建Pod(它会使用同一个PVC)
kubectl apply -f pod-with-pvc.yaml
# 检查之前写入的文件是否还在
kubectl exec -it pod-using-pvc -- cat /data/testfile.txt
# 如果成功输出 "Hello, Persistent World!",则证明PVC工作正常