13_kubernetes_concepts/13.5_practice.md
本章将通过一个具体的案例:部署一个 Nginx 网站,并为其配置 Service,来串联前面学到的知识。
开始前请先准备好可用的 Kubernetes 集群和 kubectl 上下文。你可以先完成 14.3 Docker Desktop 或 14.4 Kind,并确认:
kubectl get nodes
创建一个名为 nginx-deployment.yaml 的文件:
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.28
ports:
- containerPort: 80
应用配置:
kubectl apply -f nginx-deployment.yaml
创建一个名为 nginx-service.yaml 的文件:
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- protocol: TCP
port: 80
targetPort: 80
type: NodePort # 使用 NodePort 方便本地测试
应用配置:
kubectl apply -f nginx-service.yaml
查看分配的端口:
kubectl get svc nginx-service
如果输出端口是 80:30080/TCP,你可以通过 http://<NodeIP>:30080 访问 Nginx。Docker Desktop、Kind 等本地集群中,NodePort 到宿主机的可达性取决于集群实现;更稳定的本地访问方式是端口转发:
kubectl port-forward svc/nginx-service 8080:80
然后访问 http://localhost:8080。
Ingress 只有在集群中已安装 Ingress controller 且配置了 IngressClass 时才会生效。当前练习只覆盖 Service;Ingress/Gateway API 建议在完成第 14 章后再单独练习。
修改 nginx-deployment.yaml,将镜像版本改为 nginx:1.28-alpine。
kubectl apply -f nginx-deployment.yaml
观察更新过程:
kubectl rollout status deployment/nginx-deployment
练习结束后,记得清理资源:
kubectl delete -f nginx-service.yaml
kubectl delete -f nginx-deployment.yaml