Kubernetes 项目 #1
Source: Dev.to
概览
在 Kubernetes 中运行单个容器化的 Web 应用,并通过浏览器访问它:
流程: 浏览器 → Service → Pod → Container
本练习演示:
- 什么是 Pod
- 为什么会有 Kubernetes
- 流量如何到达容器
- Kubernetes 网络与 Docker 网络的区别
理解这些内容可以帮助你澄清许多其他 Kubernetes 概念。
前置条件
- 已安装 Minikube(本地 Kubernetes)
- 已安装
kubectl - 已安装 Docker
启动 Minikube:
minikube start
验证节点是否已就绪:
kubectl get nodes
预期输出
NAME STATUS ROLES AGE VERSION
minikube Ready control-plane ... ...
Kubernetes 总是在节点上运行工作负载,因此必须有可用的节点。
创建 Pod
创建名为 pod.yaml 的文件:
apiVersion: v1
kind: Pod
metadata:
name: hello-pod
labels:
app: hello
spec:
containers:
- name: hello-container
image: nginx
ports:
- containerPort: 80
应用该清单:
kubectl apply -f pod.yaml
检查 Pod 是否在运行:
kubectl get pods
描述 Pod 以查看分配的 IP、容器状态和事件等详细信息:
kubectl describe pod hello-pod
关键要点
- Pod 是 Kubernetes 运行的最小单元(它可以包含一个或多个容器)。
- Pod 会获得唯一的 IP 地址,但该 IP 并不稳定。
使用 Service 暴露 Pod
创建名为 service.yaml 的文件:
apiVersion: v1
kind: Service
metadata:
name: hello-service
spec:
type: NodePort
selector:
app: hello
ports:
- port: 80
targetPort: 80
nodePort: 30007
应用 Service:
kubectl apply -f service.yaml
验证 Service:
kubectl get svc
Service 提供了一个稳定的端点(NodePort),它会将流量转发到 Pod,无论 Pod 的 IP 如何变化。
访问应用
获取 Minikube 的 IP 地址:
minikube ip
在浏览器中打开以下地址:
http://<minikube-ip>:30007
你应该会看到默认的 Nginx 欢迎页面:
Welcome to nginx!
这表明 Web 应用已在 Kubernetes 中运行,并且可以从集群外部访问。
清理
删除 Pod:
kubectl delete pod hello-pod
确认它已被删除:
kubectl get pods
Pod 消失,说明单独的 Pod 并不 适合生产环境——它们在失败后不会自行恢复。
核心概念回顾
| 概念 | 描述 |
|---|---|
| Pod | 部署的最小单元;可以包含一个或多个容器。 |
| Service | 为访问 Pod 提供稳定的网络(IP/端口)入口。 |
| NodePort | 在每个节点上使用固定端口暴露 Service,实现外部访问。 |
| Labels | 键/值对,供 Service(以及其他控制器)用来选择 Pod。 |
| Deployment | 管理 ReplicaSet;确保 Pod 在宕机后自动重新创建。 |
理解 Pod、Service 和 Labels 为使用 Deployment 打下基础,后者负责在生产环境中管理 Pod 的生命周期和扩缩容。