Kubernetes集群管理入门
Kubernetes(K8s)是当前最流行的容器编排平台,本文带你理解其核心概念和常用操作。
核心概念
Pod
Pod 是 K8s 最小调度单位,包含一个或多个容器:
yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
resources:
limits:
memory: "256Mi"
cpu: "500m"Deployment
Deployment 管理 Pod 的副本集,支持滚动更新和回滚:
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web-app
spec:
replicas: 3
selector:
matchLabels:
app: web
template:
metadata:
labels:
app: web
spec:
containers:
- name: web
image: myapp:v2
ports:
- containerPort: 8080
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secret
key: urlService
Service 为一组 Pod 提供稳定的访问入口:
yaml
apiVersion: v1
kind: Service
metadata:
name: web-service
spec:
type: ClusterIP
selector:
app: web
ports:
- port: 80
targetPort: 8080Service 类型对比
| 类型 | 说明 | 访问范围 |
|---|---|---|
| ClusterIP | 集群内部IP | 集群内部 |
| NodePort | 节点端口 | 集群外部 |
| LoadBalancer | 云负载均衡器 | 公网访问 |
| Ingress | HTTP路由 | 域名访问 |
ConfigMap 与 Secret
yaml
# ConfigMap 存储配置
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
config.yaml: |
database:
host: localhost
port: 5432
redis:
host: redis-service
port: 6379 yaml
# Secret 存储敏感信息
apiVersion: v1
kind: Secret
metadata:
name: db-secret
type: Opaque
data:
password: cGFzc3dvcmQxMjM= # base64编码常用命令
bash
# 查看 Pod
kubectl get pods -o wide
# 查看 Pod 详情
kubectl describe pod <pod-name>
# 查看 Pod 日志
kubectl logs -f <pod-name>
# 进入 Pod
kubectl exec -it <pod-name> -- /bin/sh
# 扩缩容
kubectl scale deployment web-app --replicas=5
# 滚动更新
kubectl set image deployment/web-app web=myapp:v3
# 回滚
kubectl rollout undo deployment/web-app总结
Kubernetes 的学习曲线确实陡峭,但掌握 Pod、Deployment、Service 这三大核心资源后,就能应对大部分日常运维场景。建议使用 Minikube 或 Kind 在本地搭建练习环境。



评论 3