Kubernetes (K8s) 从入门到精通
·
Kubernetes (K8s) 从入门到精通
一份适合小白的 Kubernetes 学习指南,让你从零开始掌握容器编排技术
目录
第一章:Kubernetes 是什么?
1.1 为什么需要 Kubernetes?
想象一下场景:
- 你有 10 个容器运行应用
- 其中 1 个容器崩溃了怎么办?
- 流量突增,需要扩容到 100 个容器怎么办?
- 如何确保所有容器都能相互通信?
Kubernetes (K8s) 就是用来解决这些问题的!
1.2 K8s 的作用
Kubernetes 是一个容器编排平台,主要功能:
| 功能 | 说明 |
|---|---|
| 自动化部署 | 自动部署和更新应用 |
| 弹性伸缩 | 根据负载自动扩容/缩容 |
| 自愈能力 | 容器崩溃自动重启 |
| 负载均衡 | 自动分配流量 |
| 滚动更新 | 零停机更新应用 |
| 存储管理 | 自动挂载存储卷 |
1.3 K8s vs Docker
Docker:打包应用(集装箱)
K8s:管理很多容器(码头管理系统)
简单理解:
- Docker = 单个容器技术
- K8s = 管理成千上万容器的平台
第二章:核心概念详解
2.1 Pod(豆荚)
Pod 是 K8s 最小部署单元
# 一个 Pod 可以包含一个或多个容器
Pod (豌豆荚)
├── Container 1 (豌豆)
├── Container 2 (豌豆)
└── 共享网络、存储
关键特点:
- 一个 Pod 内的容器共享 IP 地址和端口
- 容器之间可以通过 localhost 直接通信
- Pod 是短暂的,随时可能被重建
2.2 Node(节点)
Node 是运行 Pod 的物理机或虚拟机
Kubernetes 集群
├── Master Node(控制节点)
│ ├── API Server(入口)
│ ├── Scheduler(调度器)
│ └── Controller Manager(控制器)
└── Worker Nodes(工作节点)
├── Pod 1
├── Pod 2
└── Pod 3
2.3 Deployment(部署)
Deployment 管理 Pod 的副本数量和更新策略
# Deployment 声明式配置
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 3 # 运行 3 个 Pod 副本
selector:
matchLabels:
app: nginx
template: # Pod 模板
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80
Deployment 能做什么?
- 确保 3 个 Pod 始终运行(即使有 Pod 崩溃)
- 滚动更新:逐个替换 Pod,实现零停机
- 回滚:快速回退到上一个版本
2.4 Service(服务)
Service 为 Pod 提供稳定的访问地址
# Service 配置示例
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- port: 80 # Service 端口
targetPort: 80 # Pod 端口
type: LoadBalancer
为什么需要 Service?
- Pod IP 会变化(Pod 重建后 IP 改变)
- Service 提供固定的 IP 和 DNS 名称
- 在多个 Pod 之间做负载均衡
2.5 ConfigMap 和 Secret
| 类型 | 用途 | 示例 |
|---|---|---|
| ConfigMap | 存储非敏感配置 | 应用配置文件、环境变量 |
| Secret | 存储敏感信息 | 密码、证书、API Key |
# ConfigMap 示例
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
database.url: "mysql:3306"
cache.size: "100mb"
第三章:环境搭建
3.1 本地学习环境(推荐新手)
方案一:Minikube(最简单)
# Windows 安装
1. 下载 Minikube: https://minikube.sigs.k8s.io/docs/start/
2. 安装 VirtualBox 或 Hyper-V
3. 启动集群
minikube start
# 验证安装
kubectl get nodes
方案二:Kind(Docker 中运行 K8s)
# 安装 Kind
choco install kind
# 创建集群
kind create cluster --name my-cluster
# 验证
kubectl cluster-info
方案三:Docker Desktop 内置 K8s
# Docker Desktop 设置中启用 Kubernetes
Settings -> Kubernetes -> Enable Kubernetes
3.2 云平台(适合生产环境)
| 平台 | 免费额度 | 特点 |
|---|---|---|
| 阿里云 ACK | 有免费试用 | 国内访问快 |
| 腾讯云 TKE | 有免费试用 | 简单易用 |
| AWS EKS | 750小时/月 | 功能强大 |
| Google GKE | 永久免费集群 | K8s 发源地 |
3.3 验证安装
# 查看 K8s 版本
kubectl version
# 查看集群信息
kubectl cluster-info
# 查看节点
kubectl get nodes
# 查看所有 Pod
kubectl get pods --all-namespaces
第四章:基础操作实战
4.1 第一个部署:Nginx
步骤 1:创建部署
# 部署 Nginx
kubectl create deployment nginx --image=nginx:1.20
# 查看 Deployment
kubectl get deployments
# 查看 Pod
kubectl get pods
步骤 2:暴露服务
# 创建 Service 暴露端口
kubectl expose deployment nginx --port=80 --type=NodePort
# 查看 Service
kubectl get services
步骤 3:访问应用
# Minikube 获取访问 URL
minikube service nginx --url
# 或通过端口转发
kubectl port-forward svc/nginx 8080:80
# 访问 http://localhost:8080
4.2 扩容应用
# 扩容到 5 个副本
kubectl scale deployment nginx --replicas=5
# 查看扩容结果
kubectl get pods
4.3 滚动更新
# 更新镜像版本
kubectl set image deployment/nginx nginx=nginx:1.21
# 查看更新状态
kubectl rollout status deployment/nginx
# 查看更新历史
kubectl rollout history deployment/nginx
4.4 回滚版本
# 回滚到上一个版本
kubectl rollout undo deployment/nginx
# 回滚到指定版本
kubectl rollout undo deployment/nginx --to-revision=2
4.5 使用 YAML 文件(推荐)
# nginx-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.20
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
selector:
app: nginx
ports:
- port: 80
targetPort: 80
type: LoadBalancer
# 应用配置
kubectl apply -f nginx-deployment.yaml
# 删除部署
kubectl delete -f nginx-deployment.yaml
4.6 常用命令速查
# 查看资源
kubectl get pods # 列出所有 Pod
kubectl get services # 列出所有 Service
kubectl get deployments # 列出所有 Deployment
kubectl get all # 列出所有资源
# 查看详情
kubectl describe pod <pod-name> # 查看 Pod 详情
kubectl logs <pod-name> # 查看 Pod 日志
kubectl logs -f <pod-name> # 实时查看日志
# 进入容器
kubectl exec -it <pod-name> -- /bin/bash # 进入容器 Shell
# 删除资源
kubectl delete pod <pod-name> # 删除 Pod
kubectl delete deployment <name> # 删除 Deployment
kubectl delete service <name> # 删除 Service
# 编辑配置
kubectl edit deployment <name> # 编辑 Deployment
kubectl apply -f config.yaml # 应用配置文件
第五章:进阶功能
5.1 Ingress(入口控制器)
Ingress 提供 HTTP/HTTPS 路由功能
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx-service
port:
number: 80
5.2 持久化存储(PV/PVC)
# PersistentVolumeClaim(存储声明)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: my-pvc
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
---
apiVersion: v1
kind: Pod
metadata:
name: storage-pod
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- mountPath: /usr/share/nginx/html
name: my-volume
volumes:
- name: my-volume
persistentVolumeClaim:
claimName: my-pvc
5.3 自动扩缩容(HPA)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: nginx-hpa
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: nginx
minReplicas: 2
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80
# 创建 HPA
kubectl autoscale deployment nginx --cpu-percent=80 --min=2 --max=10
# 查看 HPA 状态
kubectl get hpa
5.4 命名空间(Namespace)
命名空间用于资源隔离
# 创建命名空间
kubectl create namespace dev
kubectl create namespace prod
# 在指定命名空间部署
kubectl apply -f app.yaml -n dev
# 查看指定命名空间的资源
kubectl get pods -n dev
# 设置默认命名空间
kubectl config set-context --current --namespace=dev
5.5 健康检查
apiVersion: apps/v1
kind: Deployment
metadata:
name: healthy-app
spec:
replicas: 3
selector:
matchLabels:
app: healthy
template:
metadata:
labels:
app: healthy
spec:
containers:
- name: app
image: myapp:1.0
ports:
- containerPort: 8080
# 存活检查(容器健康)
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
# 就绪检查(服务可用)
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
第六章:生产环境实践
6.1 资源限制
apiVersion: v1
kind: Pod
metadata:
name: resource-pod
spec:
containers:
- name: app
image: myapp
resources:
requests: # 最小资源需求
memory: "128Mi"
cpu: "100m"
limits: # 最大资源限制
memory: "256Mi"
cpu: "500m"
6.2 配置管理最佳实践
使用 ConfigMap
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: app-config
data:
config.yml: |
database:
host: mysql
port: 3306
cache:
enabled: true
ttl: 3600
---
apiVersion: v1
kind: Pod
metadata:
name: config-pod
spec:
containers:
- name: app
image: myapp
volumeMounts:
- name: config
mountPath: /etc/config
volumes:
- name: config
configMap:
name: app-config
使用 Secret
# 创建 Secret
kubectl create secret generic db-secret \
--from-literal=username=admin \
--from-literal=password=secret123
# 在 Pod 中使用
apiVersion: v1
kind: Pod
metadata:
name: secret-pod
spec:
containers:
- name: app
image: myapp
env:
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-secret
key: username
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: db-secret
key: password
6.3 滚动更新策略
apiVersion: apps/v1
kind: Deployment
metadata:
name: rolling-update
spec:
replicas: 10
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 2 # 最多可以多创建 2 个 Pod
maxUnavailable: 1 # 最多 1 个 Pod 不可用
selector:
matchLabels:
app: myapp
template:
metadata:
labels:
app: myapp
spec:
containers:
- name: myapp
image: myapp:v1
6.4 监控和日志
安装 Metrics Server
# 安装
kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
# 查看资源使用
kubectl top nodes
kubectl top pods
日志收集
# 查看容器日志
kubectl logs <pod-name>
# 查看多个 Pod 日志
kubectl logs -l app=nginx --tail=100
# 持续监控日志
kubectl logs -f <pod-name>
6.5 安全最佳实践
apiVersion: v1
kind: Pod
metadata:
name: security-pod
spec:
securityContext:
runAsNonRoot: true # 不以 root 用户运行
runAsUser: 1000
fsGroup: 1000
containers:
- name: secure-app
image: myapp
securityContext:
allowPrivilegeEscalation: false # 禁止权限提升
readOnlyRootFilesystem: true # 只读根文件系统
capabilities:
drop: ["ALL"] # 移除所有能力
第七章:故障排查
7.1 Pod 状态排查
# 查看 Pod 状态
kubectl get pods
# 常见状态
# Pending: 正在创建
# Running: 正常运行
# Failed: 启动失败
# Unknown: 状态未知
# ImagePullBackOff: 镜像拉取失败
# CrashLoopBackOff: 容器启动后崩溃
# OOMKilled: 内存不足被杀死
# 查看 Pod 详情
kubectl describe pod <pod-name>
# 查看 Pod 事件
kubectl get events --sort-by=.metadata.creationTimestamp
7.2 常见问题及解决方案
问题 1:ImagePullBackOff
# 原因:镜像不存在或拉取失败
# 解决:
kubectl describe pod <pod-name> # 查看具体错误
# 检查镜像名称是否正确
# 检查私有仓库密钥是否配置
问题 2:CrashLoopBackOff
# 原因:容器启动后立即崩溃
# 解决:
kubectl logs <pod-name> # 查看日志
kubectl logs <pod-name> --previous # 查看上次崩溃的日志
kubectl describe pod <pod-name> # 查看配置
问题 3:Pod 无法启动(Pending)
# 检查调度问题
kubectl describe pod <pod-name>
# 常见原因:
# 1. 资源不足(内存/CPU)
# 2. 没有可用节点
# 3. 污点和容忍度配置问题
# 解决:扩容节点或降低资源请求
问题 4:Service 无法访问
# 检查 Service 配置
kubectl get endpoints <service-name>
# 检查 Pod 标签是否匹配
kubectl get pods --show-labels
# 测试 Service 连通性
kubectl run test-pod --image=busybox --rm -it -- wget -O- <service-name>
7.3 调试技巧
临时调试 Pod
# 创建临时调试 Pod
kubectl run debug-pod --image=busybox --rm -it -- sh
# 共享进程空间调试
kubectl debug -it <pod-name> --image=busybox --target=<container-name>
端口转发
# 本地访问集群服务
kubectl port-forward svc/<service-name> 8080:80
# 访问 Pod
kubectl port-forward <pod-name> 8080:8080
第八章:高级主题
8.1 Helm(包管理器)
Helm 是 K8s 的应用包管理工具
# 安装 Helm
choco install kubernetes-helm
# 添加应用仓库
helm repo add bitnami https://charts.bitnami.com/bitnami
helm repo update
# 搜索应用
helm search repo nginx
# 安装应用
helm install my-nginx bitnami/nginx
# 列出已安装应用
helm list
# 卸载应用
helm uninstall my-nginx
8.2 自定义资源(CRD)
扩展 K8s API
# 自定义资源定义
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
name: crontabs.stable.example.com
spec:
group: stable.example.com
versions:
- name: v1
served: true
storage: true
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
properties:
cronSpec:
type: string
image:
type: string
replicas:
type: integer
scope: Namespaced
names:
plural: crontabs
singular: crontab
kind: CronTab
shortNames:
- ct
8.3 Operator 模式
Operator 是使用 CRD 扩展 K8s 的模式
常用 Operator:
- Prometheus Operator:监控
- MySQL Operator:数据库管理
- Cert-Manager:证书管理
# 安装 Prometheus Operator
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/main/bundle.yaml
8.4 Service Mesh(服务网格)
Istio 是最流行的 Service Mesh
# 安装 Istio
curl -L https://istio.io/downloadIstio | sh -
cd istio-*
bin/istioctl install --set profile=demo -y
# 启用自动注入
kubectl label namespace default istio-injection=enabled
# 部署应用(自动注入 Sidecar)
kubectl apply -f app.yaml
8.5 CI/CD 集成
GitOps 工具:ArgoCD
# 安装 ArgoCD
kubectl create namespace argocd
kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
# 访问 ArgoCD UI
kubectl port-forward svc/argocd-server -n argocd 8080:443
练习项目
项目 1:个人博客系统
- Nginx 前端
- WordPress 后端
- MySQL 数据库
- 持久化存储
- Ingress 暴露
项目 2:微服务应用
- API Gateway
- 用户服务
- 订单服务
- 服务间通信
- 配置管理
项目 3:监控系统
- Prometheus + Grafana
- 数据采集
- 可视化面板
- 告警配置
推荐资源
官方文档
在线练习
书籍推荐
- 《Kubernetes 权威指南》
- 《Kubernetes in Action》
- 《云原生应用架构实践》
视频教程
学习建议
- 动手实践:边学边做,不要只看不练
- 从简单开始:先掌握基础,再学习高级功能
- 遇到问题多查日志:
kubectl describe和kubectl logs是好朋友 - 加入社区:Kubernetes 中文社区、Stack Overflow
- 关注官方:技术更新快,多看官方文档
常见问题 FAQ
Q: K8s 和 Docker Swarm 有什么区别?
A: K8s 功能更强大、生态更完善、社区更活跃,适合大规模生产环境。
Q: 学习 K8s 需要什么基础?
A: 需要了解 Docker 容器基础、Linux 基本操作、网络基础知识。
Q: 个人电脑配置低能学吗?
A: 可以,使用 Minikube 或 Kind,推荐至少 8GB 内存。
Q: K8s 就业前景如何?
A: 云原生是趋势,掌握 K8s 能显著提升职业竞争力。
Q: 需要学会编程吗?
A: 基础操作不需要,但掌握 Go/Python 会有帮助。
快速参考卡片
# 基础操作
kubectl get pods # 列出 Pod
kubectl describe pod <name> # 查看 Pod 详情
kubectl logs <name> # 查看日志
kubectl exec -it <name> -- sh # 进入容器
kubectl apply -f yaml # 应用配置
# 故障排查
kubectl get events # 查看事件
kubectl top pods # 资源使用
kubectl get endpoints # Service 端点
# 常用参数
-n <namespace> # 指定命名空间
-o wide # 详细信息
--watch # 实时监控
--all-namespaces # 所有命名空间
文档版本: v1.0
最后更新: 2026-02-027
提示: 这份文档会持续更新,欢迎收藏和分享!
如果觉得有帮助,请给个 点赞收藏 支持一下!
更多推荐
所有评论(0)