2026年 Kubernetes 入门实战指南:从本地集群到第一个应用部署
前言:为什么还要学 Kubernetes?
“都 2026 了,Kubernetes 不是标配吗?还需要专门学?”
是的,正因为它已经是标配,所以必须掌握。
现在招聘后端/运维/全栈岗位,Kubernetes 几乎成了必考项。但很多初学者被复杂概念劝退——Pod、Deployment、Service、Ingress…名字又多又抽象。
这篇文章的目的,就是让 Kubernetes 不再神秘。我会带你从零搭建本地集群、部署第一个应用、理解核心概念,建立完整的云原生思维。
一、Kubernetes 是什么?先搞懂几个核心概念
1.1 从 Docker Compose 说起
如果你用过 Docker Compose,理解 K8s 会容易很多:
Docker Compose → Kubernetes ───────────────────────────────────── container → Pod docker-compose.yml → Deployment/StatefulSet ports 映射 → Service nginx 反向代理 → Ingress volumes → PersistentVolume networks → NetworkPolicy
Pod 是 K8s 的最小调度单位。一个 Pod 可以包含一个或多个容器(通常是 Docker 容器),这些容器共享网络和存储。
1.2 K8s 架构概览
┌─────────────────────────────────────────────────────────┐ │ K8s 集群 │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Master Node │ │ Worker Node │ │ │ │ ─────────── │ │ ─────────── │ │ │ │ API Server │◄────────────►│ kubelet │ │ │ │ etcd │ │ kube-proxy │ │ │ │ Scheduler │ │ Container │ │ │ │ Controller │ │ Runtime │ │ │ └─────────────┘ └──────┬──────┘ │ │ │ │ │ ┌──────▼──────┐ │ │ │ Pods │ │ │ │ ┌───────┐ │ │ │ │ │ nginx │ │ │ │ │ └───────┘ │ │ │ └────────────┘ │ └─────────────────────────────────────────────────────────┘
Master Node(控制面):
Worker Node(工作节点):
二、快速搭建本地 Kubernetes 集群
2.1 选择合适的工具
| 工具 | 适用场景 | 系统要求 | 资源占用 |
|---|---|---|---|
| —— | ———- | ———- | ———- |
| minikube | 单节点学习 | 2核4G | 低 |
| kind (Kubernetes in Docker) | 开发测试 | 2核4G | 低 |
| k3s | 低资源环境 | 1核1G | 极低 |
| Docker Desktop K8s | Mac/Windows | 4核8G | 中 |
推荐学习使用 kind,轻量且接近真实集群。
2.2 安装 kind
macOS:
# 使用 Homebrew 安装 brew install kind # 或手动安装 curl -Lo ./kind https://kind.sigs.k8s.io/dl/v0.20.0/kind-darwin-amd64 chmod +x ./kind mv ./kind /usr/local/bin/kind
Windows(使用 PowerShell):
# 安装 kind curl.exe -Lo kind-windows-amd64.exe https://kind.sigs.k8s.io/dl/v0.20.0/kind-windows-amd64.exe Move-Item .\kind-windows-amd64.exe c:\kind.exe # 添加到 PATH $env:PATH += ";c:\"
2.3 创建集群
# 创建单节点集群
kind create cluster --name my-cluster
# 创建多节点集群(推荐)
cat > kind-config.yaml << 'EOF'
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
- role: control-plane
kubeadmConfigPatches:
- |
kind: InitConfiguration
nodeRegistration:
kubeletExtraArgs:
node-labels: "ingress-ready=true"
extraPortMappings:
- containerPort: 80
hostPort: 80
protocol: TCP
- containerPort: 443
hostPort: 443
protocol: TCP
- role: worker
- role: worker
EOF
kind create cluster --name my-cluster --config kind-config.yaml
2.4 验证集群
# 查看集群信息 kubectl cluster-info # 查看节点 kubectl get nodes # 输出示例 NAME STATUS ROLES AGE VERSION my-cluster-control-plane Ready control-plane 5m v1.29.0 my-cluster-worker Ready <none> 4m v1.29.0 my-cluster-worker2 Ready <none> 4m v1.29.0
三、部署第一个应用
3.1 创建 Deployment
Deployment 是 K8s 最常用的 workload,用于声明式管理 Pod 副本。
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3 # 3 个副本
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.25-alpine
ports:
- containerPort: 80
resources:
limits:
memory: "128Mi"
cpu: "500m"
requests:
memory: "64Mi"
cpu: "250m"
3.2 部署应用
# 应用 Deployment kubectl apply -f deployment.yaml # 查看部署状态 kubectl get deployments # 查看 Pod kubectl get pods # 查看 Pod 详情 kubectl describe pod nginx-deployment-7fb96c846b-xxxxx # 查看 Pod 日志 kubectl logs nginx-deployment-7fb96c846b-xxxxx
3.3 暴露服务(创建 Service)
Service 为一组 Pod 提供稳定的访问入口。
# service.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: ClusterIP # ClusterIP / NodePort / LoadBalancer
selector:
app: nginx
ports:
- protocol: TCP
port: 80 # Service 端口
targetPort: 80 # 容器端口
kubectl apply -f service.yaml # 查看 Service kubectl get services
3.4 访问应用
由于是本地集群,需要通过端口转发访问:
# 端口转发 kubectl port-forward svc/nginx-service 8080:80 # 然后访问 http://localhost:8080
四、核心概念详解
4.1 Deployment 的工作原理
Deployment
│
├── 创建 ReplicaSet
│ │
│ └── 创建 Pod(3个副本)
│ │
│ └── 创建容器
│
└── 滚动更新
│
├── 新 ReplicaSet(逐步增加副本)
└── 旧 ReplicaSet(逐步减少副本)
滚动更新策略:
spec:
strategy:
type: RollingUpdate
rollingUpdate:
maxSurge: 1 # 最多超出期望副本数
maxUnavailable: 0 # 最多不可用副本数
4.2 Service 类型对比
| 类型 | 适用场景 | 访问方式 |
|---|---|---|
| —— | ———- | ———- |
| ClusterIP | 集群内部通信 | 内部 IP(10.96.0.x) |
| NodePort | 开发测试 | |
| LoadBalancer | 云环境 | 云厂商 LB |
| ExternalName | 外部服务映射 | DNS 名称 |
4.3 ConfigMap 与 Secret
ConfigMap:存储非敏感配置
apiVersion: v1 kind: ConfigMap metadata: name: app-config data: DATABASE_HOST: "db.example.com" LOG_LEVEL: "info"
Secret:存储敏感信息(Base64 编码)
apiVersion: v1 kind: Secret metadata: name: app-secret type: Opaque data: # echo -n "password123" | base64 DB_PASSWORD: cGFzc3dvcmQxMjM=
在 Pod 中使用:
spec:
containers:
- name: app
envFrom:
- configMapRef:
name: app-config
env:
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: app-secret
key: DB_PASSWORD
4.4 Ingress(入口路由)
Ingress 相当于 K8s 集群的”入口网关”,用于 HTTP/HTTPS 路由。
# 安装 Ingress Controller(以 nginx 为例)
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.9.0/deploy/static/provider/cloud/deploy.yaml
# 定义 Ingress 规则
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
spec:
ingressClassName: nginx
rules:
- host: app.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx-service
port:
number: 80
五、实战:部署一个完整应用
5.1 场景说明
部署一个 Web API 应用,包含:
5.2 目录结构
my-app/ ├── frontend/ │ ├── deployment.yaml │ └── service.yaml ├── backend/ │ ├── deployment.yaml │ ├── service.yaml │ ├── configmap.yaml │ └── secret.yaml ├── database/ │ ├── statefulset.yaml │ └── service.yaml └── ingress.yaml
5.3 数据库 StatefulSet
# database/statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: postgres
spec:
serviceName: postgres
replicas: 1
selector:
matchLabels:
app: postgres
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres
image: postgres:15-alpine
ports:
- containerPort: 5432
env:
- name: POSTGRES_DB
value: myapp
- name: POSTGRES_USER
value: admin
- name: POSTGRES_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
volumeMounts:
- name: data
mountPath: /var/lib/postgresql/data
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
resources:
requests:
storage: 1Gi
5.4 后端 Deployment
# backend/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
replicas: 2
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: backend
image: myregistry/backend:v1.0.0
ports:
- containerPort: 8000
env:
- name: DATABASE_URL
value: "postgresql://admin:$(DB_PASSWORD)@postgres:5432/myapp"
- name: DB_PASSWORD
valueFrom:
secretKeyRef:
name: postgres-secret
key: password
readinessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
httpGet:
path: /health
port: 8000
initialDelaySeconds: 30
periodSeconds: 10
5.5 统一部署
# 创建 namespace kubectl create namespace myapp # 部署所有资源 kubectl apply -n myapp -f ./database kubectl apply -n myapp -f ./backend kubectl apply -n myapp -f ./frontend # 查看所有资源 kubectl get all -n myapp # 查看 Pod 日志 kubectl logs -n myapp -l app=backend -f
六、日常运维命令速查
6.1 资源管理
# 获取资源 kubectl get pods -n <namespace> kubectl get deployments -n <namespace> kubectl get services -n <namespace> kubectl get ingress -n <namespace> # 查看详细 kubectl describe pod <pod-name> -n <namespace> kubectl describe deployment <deployment-name> -n <namespace> # 删除资源 kubectl delete -f <yaml-file> kubectl delete pod <pod-name> -n <namespace> # 扩缩容 kubectl scale deployment <deployment-name> --replicas=5 -n <namespace>
6.2 调试与排障
# 进入容器(调试用) kubectl exec -it <pod-name> -n <namespace> -- /bin/sh # 查看日志 kubectl logs <pod-name> -n <namespace> kubectl logs <pod-name> -n <namespace> --previous # 上一个容器实例 # 端口转发(本地调试) kubectl port-forward <pod-name> 8080:80 -n <namespace> # 资源使用 kubectl top pod -n <namespace> kubectl top node
6.3 滚动更新与回滚
# 查看部署历史 kubectl rollout history deployment/<name> -n <namespace> # 回滚到上一个版本 kubectl rollout undo deployment/<name> -n <namespace> # 回滚到指定版本 kubectl rollout undo deployment/<name> --to-revision=2 -n <namespace>
七、学习路径建议
阶段一:入门(1-2周)
阶段二:进阶(3-4周)
阶段三:生产级(5-8周)
阶段四:认证
总结
本文覆盖了 Kubernetes 入门所需的核心知识点:
1. 概念理解:Pod、Deployment、Service、Ingress 的作用与关系
2. 环境搭建:使用 kind 快速创建本地集群
3. 实战部署:从单应用到多组件完整部署
4. 运维命令:日常调试与排障常用命令
5. 学习路径:系统化提升的建议
Kubernetes 的学习曲线确实存在,但只要动手实践,很快就能建立直观理解。建议找一个周末,从头到尾跟着本文操作一遍,比看十篇文章都有用。
关于作者
长期关注大模型应用落地与云服务器实战,专注技术在企业场景中的落地实践。
个人博客:yunduancloud.icu —— 持续更新云计算、AI大模型实战教程,欢迎访问交流。
