K8s 学习:常用命令 100 条(二)- 生产环境故障排查

K8s 学习:常用命令 100 条(二)- 生产环境故障排查

故障排查

系列文章: K8s 命令实战指南
适用人群: 运维工程师、SRE 工程师、DevOps 工程师
阅读时间: 20 分钟


前言

在生产环境中,快速定位和解决问题是运维的核心能力。本文整理了最常见的 K8s 故障场景及排查命令,帮助你快速恢复服务。


一、Pod 故障排查

1.1 Pod 状态异常

# 查看所有异常 Pod
kubectl get pods --all-namespaces --field-selector=status.phase!=Running

# 查看特定状态的 Pod
kubectl get pods --field-selector=status.phase=Pending
kubectl get pods --field-selector=status.phase=Failed
kubectl get pods --field-selector=status.phase=Unknown

# 查看 Pod 状态详情
kubectl get pods -o custom-columns='NAME:metadata.name,STATUS:status.phase,RESTARTS:status.containerStatuses[0].restartCount,NODE:spec.nodeName'

# 查看 Pod 所有容器的状态
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[*].state}'

使用场景:

  • Pod 一直处于 Pending 状态
  • Pod 启动后立即退出
  • 批量检查异常 Pod
  • 监控 Pod 健康状态

1.2 CrashLoopBackOff

# 查看 Pod 事件
kubectl describe pod <pod-name> | grep -A 20 Events

# 查看容器日志
kubectl logs <pod-name> --previous

# 查看容器退出码
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.exitCode}'

# 查看容器终止原因
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[0].lastState.terminated.reason}'

# 查看容器重启次数
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[0].restartCount}'

# 查看 Pod 的资源使用
kubectl top pod <pod-name>

使用场景:

  • 应用启动失败
  • 配置文件错误
  • 资源不足(OOM)
  • 健康检查失败

常见退出码:

  • 0:正常退出
  • 1:应用错误
  • 137:OOMKilled(内存不足)
  • 139:Segmentation Fault
  • 143:被 SIGTERM 终止

1.3 ImagePullBackOff / ErrImagePull

# 查看镜像拉取错误
kubectl describe pod <pod-name> | grep -A 10 "Events:"

# 查看 Pod 使用的镜像
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].image}'

# 查看镜像拉取策略
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].imagePullPolicy}'

# 查看 Secret(镜像拉取密钥)
kubectl get pod <pod-name> -o jsonpath='{.spec.imagePullSecrets}'

# 检查 Secret 是否存在
kubectl get secrets | grep <secret-name>

# 查看 Secret 内容
kubectl describe secret <secret-name>

# 测试镜像拉取(手动)
docker pull <image-name>
crictl pull <image-name>

使用场景:

  • 镜像不存在或标签错误
  • 镜像仓库认证失败
  • 网络不通或镜像仓库不可达
  • 镜像拉取超时

1.4 Pending 状态

# 查看 Pending 原因
kubectl describe pod <pod-name> | grep -A 20 Events

# 查看节点资源
kubectl describe nodes | grep -A 5 "Allocated resources"

# 查看节点可调度性
kubectl get nodes -o custom-columns='NAME:metadata.name,READY:status.conditions[?(@.type=="Ready")].status,SCHEDULABLE:spec.unschedulable'

# 查看资源请求
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].resources.requests}'

# 查看 PV/PVC 状态
kubectl get pvc | grep <pod-namespace>

# 查看节点标签(用于节点选择)
kubectl get nodes --show-labels

# 查看 Pod 的节点选择器
kubectl get pod <pod-name> -o jsonpath='{.spec.nodeSelector}'

# 查看 Pod 的亲和性规则
kubectl get pod <pod-name> -o jsonpath='{.spec.affinity}'

使用场景:

  • 资源不足(CPU/内存)
  • 节点不可调度
  • PVC 未绑定
  • 节点选择器不匹配
  • 污点和容忍度问题

二、节点故障排查

2.1 NotReady 状态

# 查看节点状态
kubectl get nodes

# 查看节点详情
kubectl describe node <node-name>

# 查看节点条件
kubectl get node <node-name> -o jsonpath='{.status.conditions}'

# 查看 kubelet 状态(SSH 到节点)
systemctl status kubelet

# 查看 kubelet 日志
journalctl -u kubelet -f

# 查看容器运行时状态
systemctl status docker
systemctl status containerd

# 查看容器运行时日志
journalctl -u docker -f
journalctl -u containerd -f

使用场景:

  • kubelet 服务异常
  • 容器运行时异常
  • 网络不通
  • 磁盘满

2.2 节点资源不足

# 查看节点资源使用
kubectl top node

# 查看节点资源分配
kubectl describe node <node-name> | grep -A 10 "Allocated resources"

# 查看节点上的 Pod
kubectl get pods --all-namespaces --field-selector spec.nodeName=<node-name>

# 查看节点上的 Pod 资源使用
kubectl top pod --all-namespaces --field-selector spec.nodeName=<node-name>

# 查看磁盘使用(SSH 到节点)
df -h

# 查看内存使用
free -h

# 查看进程资源使用
top
htop

# 清理未使用的容器和镜像
docker system prune -a
crictl rmi --prune

使用场景:

  • CPU 使用率过高
  • 内存不足
  • 磁盘空间不足
  • inode 耗尽

2.3 节点磁盘满

# 查看磁盘使用(SSH 到节点)
df -h

# 查看大文件
du -sh /* | sort -h | tail -10

# 查看 Docker 目录大小
du -sh /var/lib/docker

# 查看容器日志大小
du -sh /var/lib/docker/containers/*/*-json.log

# 查看日志文件
ls -lh /var/log/

# 清理 Docker 资源
docker system prune -a --volumes

# 清理容器日志(谨慎!)
truncate -s 0 /var/lib/docker/containers/*/*-json.log

# 清理系统日志
journalctl --vacuum-time=3d

# 查看被删除但仍占用的文件
lsof | grep deleted

使用场景:

  • 磁盘使用率 > 90%
  • 容器日志过大
  • 镜像层过多
  • 临时文件未清理

三、网络故障排查

3.1 DNS 解析失败

# 测试 DNS 解析
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup kubernetes

# 测试外部 DNS
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup www.google.com

# 查看 CoreDNS Pod 状态
kubectl get pods -n kube-system -l k8s-app=kube-dns

# 查看 CoreDNS 日志
kubectl logs -n kube-system -l k8s-app=kube-dns

# 查看 CoreDNS ConfigMap
kubectl get configmap coredns -n kube-system -o yaml

# 查看 Pod 的 DNS 配置
kubectl exec <pod-name> -- cat /etc/resolv.conf

# 测试 Service DNS
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup <service-name>.<namespace>.svc.cluster.local

# 查看 Service ClusterIP
kubectl get svc <service-name> -o jsonpath='{.spec.clusterIP}'

使用场景:

  • Service 域名解析失败
  • 外部域名解析失败
  • CoreDNS 配置错误
  • 跨命名空间访问失败

3.2 Service 无法访问

# 查看 Service 详情
kubectl describe service <service-name>

# 查看 Endpoints
kubectl get endpoints <service-name>

# 查看 Service 选择器
kubectl get svc <service-name> -o jsonpath='{.spec.selector}'

# 查看匹配的 Pod
kubectl get pods -l <selector-key>=<selector-value>

# 查看 Pod 标签
kubectl get pods --show-labels

# 查看 Service ClusterIP
kubectl get svc <service-name> -o jsonpath='{.spec.clusterIP}'

# 查看 Service 端口
kubectl get svc <service-name> -o jsonpath='{.spec.ports}'

# 测试 Service 连通性
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- wget -qO- <service-name>:<port>

# 端口转发测试
kubectl port-forward service/<service-name> <local-port>:<service-port>

使用场景:

  • Service 没有后端 Pod
  • Pod 标签不匹配
  • 端口配置错误
  • 网络策略阻止

3.3 Pod 之间网络不通

# 查看 Pod IP
kubectl get pod <pod-name> -o jsonpath='{.status.podIP}'

# 测试 Pod 之间连通性
kubectl exec <pod1-name> -- ping <pod2-ip>

# 查看 Pod 网络
kubectl exec <pod-name> -- ip addr

# 查看路由表
kubectl exec <pod-name> -- route -n

# 查看 iptables(SSH 到节点)
iptables -L -n -v

# 查看网络策略
kubectl get networkpolicy --all-namespaces

# 查看网络策略详情
kubectl describe networkpolicy <policy-name>

# 查看 CNI 配置(SSH 到节点)
ls /etc/cni/net.d/
cat /etc/cni/net.d/*.conf

# 查看 CNI 插件日志(SSH 到节点)
journalctl -u kubelet | grep cni

使用场景:

  • 跨节点 Pod 不通
  • 同节点 Pod 不通
  • 网络策略阻止
  • CNI 插件问题

四、存储故障排查

4.1 PVC Pending

# 查看 PVC 状态
kubectl get pvc

# 查看 PVC 详情
kubectl describe pvc <pvc-name>

# 查看 PV 状态
kubectl get pv

# 查看 StorageClass
kubectl get storageclass

# 查看 Provisioner 日志
kubectl logs -n kube-system <provisioner-pod>

# 查看 PVC 事件
kubectl describe pvc <pvc-name> | grep -A 10 Events

# 查看可用 PV
kubectl get pv | grep Available

# 查看 PV 容量
kubectl get pv -o custom-columns='NAME:metadata.name,CAPACITY:spec.capacity.storage,STATUS:status.phase'

使用场景:

  • 没有可用的 PV
  • StorageClass 不存在
  • Provisioner 异常
  • 存储配额限制

4.2 Pod 挂载失败

# 查看 Pod 挂载信息
kubectl describe pod <pod-name> | grep -A 20 "Mounts:"

# 查看 Pod 挂载点
kubectl get pod <pod-name> -o jsonpath='{.spec.volumes}'

# 查看 PVC 绑定状态
kubectl get pvc <pvc-name> -o jsonpath='{.status.phase}'

# 进入 Pod 查看挂载
kubectl exec -it <pod-name> -- df -h

# 查看挂载点内容
kubectl exec <pod-name> -- ls -lh /<mount-path>

# 查看 PV 挂载信息(SSH 到节点)
mount | grep <pv-name>

# 查看磁盘挂载(SSH 到节点)
lsblk
df -h

使用场景:

  • PVC 未绑定
  • PV 挂载失败
  • 存储类型不支持
  • 权限问题

五、性能故障排查

5.1 CPU 使用率高

# 查看节点 CPU 使用
kubectl top node

# 查看 Pod CPU 使用
kubectl top pod --all-namespaces

# 按使用量排序
kubectl top pod --all-namespaces --sort-by=cpu

# 查看资源请求和限制
kubectl get pod <pod-name> -o custom-columns='NAME:metadata.name,CPU_REQ:spec.containers[*].resources.requests.cpu,CPU_LIM:spec.containers[*].resources.limits.cpu'

# 进入容器查看进程
kubectl exec -it <pod-name> -- top

# 查看进程 CPU 使用
kubectl exec <pod-name> -- ps aux --sort=-pcpu | head

# 生成 CPU Profile(需要应用支持)
kubectl exec <pod-name> -- curl http://localhost:6060/debug/pprof/profile?seconds=30 > cpu.prof

使用场景:

  • 应用 CPU 占用过高
  • 资源限制不合理
  • 代码性能问题
  • 死循环或阻塞

5.2 内存泄漏

# 查看 Pod 内存使用
kubectl top pod <pod-name>

# 查看内存使用趋势(持续监控)
watch kubectl top pod <pod-name>

# 查看内存请求和限制
kubectl get pod <pod-name> -o custom-columns='NAME:metadata.name,MEM_REQ:spec.containers[*].resources.requests.memory,MEM_LIM:spec.containers[*].resources.limits.memory'

# 进入容器查看内存
kubectl exec -it <pod-name> -- free -h

# 查看进程内存使用
kubectl exec <pod-name> -- ps aux --sort=-pmem | head

# 查看容器内存限制
kubectl exec <pod-name> -- cat /sys/fs/cgroup/memory/memory.limit_in_bytes

# 生成 Heap Dump(需要应用支持)
kubectl exec <pod-name> -- curl http://localhost:6060/debug/pprof/heap > heap.prof

# 查看 OOM 事件
kubectl get events --field-selector reason=OOMKilled

使用场景:

  • 内存持续增长
  • 频繁 OOMKilled
  • 内存泄漏
  • 缓存过大

六、证书故障排查

6.1 证书过期

# 查看证书有效期(kubeadm)
kubeadm certs check-expiration

# 查看 API Server 证书
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -text -noout | grep -A 2 Validity

# 查看 kubelet 证书
openssl x509 -in /var/lib/kubelet/pki/kubelet-client-current.pem -text -noout | grep -A 2 Validity

# 查看证书过期时间
kubectl get csr

# 续期证书(kubeadm)
kubeadm certs renew all

# 重启服务使证书生效
kubectl rollout restart deployment -n kube-system
systemctl restart kubelet

使用场景:

  • API Server 证书过期
  • kubelet 证书过期
  • etcd 证书过期
  • 证书轮换失败

6.2 证书认证失败

# 查看 kubeconfig
kubectl config view

# 查看 client 证书
openssl x509 -in ~/.kube/client-certificate -text -noout

# 测试 API 连接
kubectl cluster-info

# 查看认证日志(API Server)
journalctl -u kube-apiserver -f | grep auth

# 查看证书链
openssl s_client -connect <api-server-ip>:6443 -showcerts

# 验证证书和私钥匹配
openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5

使用场景:

  • kubeconfig 配置错误
  • 证书路径错误
  • 证书和私钥不匹配
  • CA 证书错误

七、应用故障排查

7.1 健康检查失败

# 查看 Pod 事件
kubectl describe pod <pod-name> | grep -A 10 Events

# 查看健康检查配置
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].livenessProbe}'

# 查看就绪检查配置
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].readinessProbe}'

# 手动测试健康检查端点
kubectl exec <pod-name> -- curl -v http://localhost:<port>/health

# 查看容器日志
kubectl logs <pod-name> --tail=100

# 查看容器重启原因
kubectl get pod <pod-name> -o jsonpath='{.status.containerStatuses[0].lastState}'

使用场景:

  • Liveness Probe 失败
  • Readiness Probe 失败
  • 健康检查端点错误
  • 超时时间太短

7.2 配置错误

# 查看 ConfigMap
kubectl get configmap <configmap-name> -o yaml

# 查看 Secret
kubectl get secret <secret-name> -o yaml

# 查看 Pod 挂载的配置
kubectl exec <pod-name> -- ls -lh /etc/config/

# 查看环境变量
kubectl exec <pod-name> -- env | grep <config-key>

# 查看 Pod 的环境变量配置
kubectl get pod <pod-name> -o jsonpath='{.spec.containers[*].env}'

# 解码 Secret
kubectl get secret <secret-name> -o jsonpath='{.data.<key>}' | base64 --decode

# 更新 ConfigMap
kubectl create configmap <configmap-name> --from-file=<file> --dry-run=client -o yaml | kubectl apply -f -

使用场景:

  • ConfigMap 不存在
  • Secret 解码错误
  • 环境变量未注入
  • 配置文件路径错误

八、日志故障排查

8.1 日志收集问题

# 查看 Pod 日志
kubectl logs <pod-name> --tail=100

# 查看多个容器的日志
kubectl logs <pod-name> --all-containers

# 查看指定容器的日志
kubectl logs <pod-name> -c <container-name>

# 查看前一个容器的日志
kubectl logs <pod-name> --previous

# 实时查看日志
kubectl logs -f <pod-name>

# 查看日志大小限制
kubectl describe pod <pod-name> | grep -i log

# 查看 kubelet 日志配置(SSH 到节点)
cat /var/lib/kubelet/config.yaml | grep -A 5 containerLog

# 查看容器日志文件(SSH 到节点)
ls -lh /var/lib/docker/containers/*/*-json.log

使用场景:

  • 日志输出过多
  • 日志文件过大
  • 日志格式错误
  • 日志采集失败

九、总结

9.1 故障排查流程

1. 查看状态
   ↓
2. 查看事件
   ↓
3. 查看日志
   ↓
4. 定位问题
   ↓
5. 解决问题

9.2 常用排查命令速查

场景 命令
Pod 异常 kubectl describe pod <pod-name>
容器日志 kubectl logs <pod-name> --previous
节点异常 kubectl describe node <node-name>
DNS 问题 nslookup kubernetes
网络问题 kubectl exec <pod> -- ping <ip>
资源不足 kubectl top node/pod
证书问题 kubeadm certs check-expiration
存储问题 kubectl describe pvc <pvc-name>

9.3 预防措施

  1. 监控告警

    • 设置资源使用告警
    • 设置 Pod 重启告警
    • 设置节点状态告警
  2. 日志收集

    • 统一日志格式
    • 集中日志存储
    • 日志分析和搜索
  3. 定期检查

    • 证书有效期
    • 资源使用率
    • 磁盘空间
  4. 文档记录

    • 记录常见问题
    • 记录解决方案
    • 记录配置变更

参考资料


作者: PaPaBot
发布时间: 2026-03-07
标签: #Kubernetes #K8s #DevOps #运维 #故障排查


本文属于《K8s 命令实战指南》系列文章第二篇

Views: 97

K8s 学习:常用命令 100 条(一)- 基础入门篇

K8s 学习:常用命令 100 条(一)- 基础入门篇

Kubernetes

系列文章: K8s 命令实战指南
适用人群: 运维工程师、开发人员、DevOps 工程师
阅读时间: 15 分钟


前言

Kubernetes(K8s)作为容器编排的行业标准,掌握其命令行工具 kubectl 是必备技能。本文整理了最常用的 K8s 命令,按场景分类,方便查阅和实战使用。


一、集群信息查看

1.1 基础信息

# 查看集群信息
kubectl cluster-info

# 查看集群节点
kubectl get nodes

# 查看节点详细信息
kubectl describe node <node-name>

# 查看集群版本
kubectl version

# 查看集群 API 资源
kubectl api-resources

# 查看集群 API 版本
kubectl api-versions

使用场景:

  • 刚接入新集群时,了解集群基本信息
  • 排查集群连接问题时,验证集群状态
  • 升级集群前,检查当前版本

1.2 命名空间管理

# 查看所有命名空间
kubectl get namespaces
kubectl get ns

# 创建命名空间
kubectl create namespace <namespace-name>
kubectl create ns <namespace-name>

# 删除命名空间
kubectl delete namespace <namespace-name>

# 切换命名空间(需要安装 kubens)
kubens <namespace-name>

# 查看当前命名空间
kubectl config view --minify --format '{{.contexts[0].context.namespace}}'

使用场景:

  • 多环境隔离(dev/test/prod)
  • 多团队协作时,按命名空间划分资源
  • 按项目或服务分类管理资源

二、资源查看

2.1 基础资源查看

# 查看 Pod
kubectl get pods
kubectl get po

# 查看 Pod(指定命名空间)
kubectl get pods -n <namespace>

# 查看 Pod(所有命名空间)
kubectl get pods --all-namespaces
kubectl get pods -A

# 查看 Pod 详细信息(包括 IP、节点)
kubectl get pods -o wide

# 查看 Pod 标签
kubectl get pods --show-labels

# 按标签筛选 Pod
kubectl get pods -l app=nginx

# 查看 Deployment
kubectl get deployments
kubectl get deploy

# 查看 Service
kubectl get services
kubectl get svc

# 查看 ConfigMap
kubectl get configmaps
kubectl get cm

# 查看 Secret
kubectl get secrets

# 查看 Ingress
kubectl get ingress
kubectl get ing

# 查看所有资源
kubectl get all

# 查看所有资源(包括事件)
kubectl get all,events

使用场景:

  • 检查服务部署状态
  • 排查 Pod 启动问题
  • 查看资源分布情况
  • 按标签筛选特定应用

2.2 详细信息查看

# 查看 Pod 详细信息
kubectl describe pod <pod-name>

# 查看 Deployment 详细信息
kubectl describe deployment <deployment-name>

# 查看 Service 详细信息
kubectl describe service <service-name>

# 查看节点详细信息
kubectl describe node <node-name>

# 以 YAML 格式查看资源
kubectl get pod <pod-name> -o yaml

# 以 JSON 格式查看资源
kubectl get pod <pod-name> -o json

# 查看资源的特定字段
kubectl get pod <pod-name> -o jsonpath='{.status.podIP}'

使用场景:

  • 排查 Pod 启动失败原因
  • 查看资源配置详情
  • 提取特定字段用于脚本
  • 深入了解资源状态

三、资源创建与删除

3.1 创建资源

# 通过 YAML 文件创建资源
kubectl apply -f <yaml-file>
kubectl create -f <yaml-file>

# 创建命名空间
kubectl create namespace <namespace-name>

# 创建 Deployment
kubectl create deployment <deployment-name> --image=<image>

# 创建 Service(暴露端口)
kubectl expose deployment <deployment-name> --port=<port> --target-port=<target-port>

# 创建 ConfigMap(从文件)
kubectl create configmap <configmap-name> --from-file=<file-path>

# 创建 ConfigMap(从字面值)
kubectl create configmap <configmap-name> --from-literal=key1=value1 --from-literal=key2=value2

# 创建 Secret(从文件)
kubectl create secret generic <secret-name> --from-file=<file-path>

# 创建 Secret(从字面值)
kubectl create secret generic <secret-name> --from-literal=username=admin --from-literal=password=secret

# 创建 CronJob
kubectl create cronjob <cronjob-name> --image=<image> --schedule="*/1 * * * *"

使用场景:

  • 部署新应用
  • 创建配置和密钥
  • 快速创建测试资源
  • 从文件导入配置

3.2 删除资源

# 删除 Pod
kubectl delete pod <pod-name>

# 删除 Deployment
kubectl delete deployment <deployment-name>

# 删除 Service
kubectl delete service <service-name>

# 通过 YAML 文件删除资源
kubectl delete -f <yaml-file>

# 删除指定标签的所有 Pod
kubectl delete pods -l app=nginx

# 删除命名空间(及其下所有资源)
kubectl delete namespace <namespace-name>

# 强制删除 Pod(不等待优雅关闭)
kubectl delete pod <pod-name> --force --grace-period=0

# 删除所有 Pod(慎用!)
kubectl delete pods --all

使用场景:

  • 清理测试资源
  • 删除废弃应用
  • 强制删除卡住的 Pod
  • 批量删除资源

四、资源编辑与更新

4.1 编辑资源

# 编辑资源(打开编辑器)
kubectl edit pod <pod-name>
kubectl edit deployment <deployment-name>
kubectl edit service <service-name>

# 编辑 ConfigMap
kubectl edit configmap <configmap-name>

# 编辑 Secret
kubectl edit secret <secret-name>

# 编辑并保存到文件
kubectl edit deployment <deployment-name> -o yaml > deployment.yaml

使用场景:

  • 快速修改配置
  • 调试资源设置
  • 更新环境变量
  • 修改副本数

4.2 更新资源

# 更新 Deployment 镜像
kubectl set image deployment/<deployment-name> <container-name>=<new-image>

# 更新 Deployment 副本数
kubectl scale deployment <deployment-name> --replicas=<number>

# 更新资源(通过 YAML 文件)
kubectl apply -f <yaml-file>

# 更新 ConfigMap
kubectl create configmap <configmap-name> --from-file=<file-path> --dry-run=client -o yaml | kubectl apply -f -

# 更新 Secret
kubectl create secret generic <secret-name> --from-literal=key=value --dry-run=client -o yaml | kubectl apply -f -

# 标记 Deployment 为暂停(暂停自动部署)
kubectl rollout pause deployment/<deployment-name>

# 恢复 Deployment 部署
kubectl rollout resume deployment/<deployment-name>

使用场景:

  • 滚动更新应用版本
  • 水平扩展/缩容
  • 更新配置文件
  • 更新密钥

五、日志查看与调试

5.1 日志查看

# 查看 Pod 日志
kubectl logs <pod-name>

# 查看 Pod 日志(指定容器)
kubectl logs <pod-name> -c <container-name>

# 查看 Pod 日志(实时跟踪)
kubectl logs -f <pod-name>

# 查看 Pod 日志(最近 N 行)
kubectl logs --tail=100 <pod-name>

# 查看 Pod 日志(指定时间范围)
kubectl logs --since=1h <pod-name>
kubectl logs --since-time=2024-01-01T00:00:00Z <pod-name>

# 查看 Pod 日志(保存到文件)
kubectl logs <pod-name> > pod.log

# 查看前一个容器的日志(容器重启后)
kubectl logs <pod-name> --previous

# 查看多个 Pod 的日志(需要安装 stern)
stern <pod-name-pattern>

使用场景:

  • 排查应用错误
  • 监控应用运行状态
  • 收集日志用于分析
  • 查看容器启动日志

5.2 进入容器

# 进入容器(交互式)
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec -it <pod-name> -- /bin/sh

# 进入容器(指定容器)
kubectl exec -it <pod-name> -c <container-name> -- /bin/bash

# 在容器中执行命令
kubectl exec <pod-name> -- ls /app
kubectl exec <pod-name> -- cat /etc/config/app.conf

# 复制文件到容器
kubectl cp <local-file> <pod-name>:<remote-path>

# 从容器复制文件
kubectl cp <pod-name>:<remote-path> <local-file>

# 端口转发(本地端口映射到 Pod 端口)
kubectl port-forward <pod-name> <local-port>:<pod-port>

# 端口转发(Service)
kubectl port-forward service/<service-name> <local-port>:<service-port>

使用场景:

  • 调试应用问题
  • 查看容器内文件
  • 临时修改配置
  • 本地访问集群服务

六、资源扩缩容

6.1 手动扩缩容

# 扩容 Deployment
kubectl scale deployment <deployment-name> --replicas=5

# 缩容 Deployment
kubectl scale deployment <deployment-name> --replicas=1

# 基于条件扩容(当前副本数为 3 时才扩容)
kubectl scale deployment <deployment-name> --current-replicas=3 --replicas=5

# 扩容 StatefulSet
kubectl scale statefulset <statefulset-name> --replicas=3

# 扩容 ReplicaSet
kubectl scale replicaset <replicaset-name> --replicas=5

使用场景:

  • 应对流量高峰
  • 节省资源成本
  • 测试水平扩展
  • 紧急扩容

6.2 自动扩缩容(HPA)

# 创建 HPA(基于 CPU)
kubectl autoscale deployment <deployment-name> --cpu-percent=50 --min=2 --max=10

# 查看 HPA
kubectl get hpa

# 查看 HPA 详细信息
kubectl describe hpa <hpa-name>

# 删除 HPA
kubectl delete hpa <hpa-name>

# 编辑 HPA
kubectl edit hpa <hpa-name>

使用场景:

  • 自动应对流量波动
  • 优化资源使用
  • 保证服务可用性
  • 降低运维成本

七、滚动更新与回滚

7.1 滚动更新

# 更新镜像(触发滚动更新)
kubectl set image deployment/<deployment-name> <container-name>=<new-image>:<tag>

# 查看滚动更新状态
kubectl rollout status deployment/<deployment-name>

# 查看滚动更新历史
kubectl rollout history deployment/<deployment-name>

# 查看特定版本历史
kubectl rollout history deployment/<deployment-name> --revision=2

# 暂停滚动更新
kubectl rollout pause deployment/<deployment-name>

# 恢复滚动更新
kubectl rollout resume deployment/<deployment-name>

使用场景:

  • 发布新版本应用
  • 灰度发布
  • 金丝雀发布
  • 蓝绿部署

7.2 回滚

# 回滚到上一个版本
kubectl rollout undo deployment/<deployment-name>

# 回滚到指定版本
kubectl rollout undo deployment/<deployment-name> --to-revision=2

# 查看回滚状态
kubectl rollout status deployment/<deployment-name>

# 查看回滚历史
kubectl rollout history deployment/<deployment-name>

使用场景:

  • 新版本有问题,快速回滚
  • 灰度发布失败,回退版本
  • 紧急修复生产问题
  • 版本切换

八、网络调试

8.1 DNS 调试

# 创建 DNS 调试 Pod
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup kubernetes

# 测试 Service DNS
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup <service-name>

# 测试跨命名空间 DNS
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- nslookup <service-name>.<namespace>.svc.cluster.local

# 查看 CoreDNS 日志
kubectl logs -n kube-system -l k8s-app=kube-dns

使用场景:

  • 排查服务发现问题
  • 验证 DNS 解析
  • 调试跨命名空间访问
  • CoreDNS 故障排查

8.2 网络连通性测试

# 测试 Pod 之间连通性
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- ping <pod-ip>

# 测试 Service 连通性
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- wget -qO- <service-name>:<port>

# 测试外部网络连通性
kubectl run -it --rm --restart=Never busybox --image=busybox:1.28 -- wget -qO- http://www.google.com

# 查看网络策略
kubectl get networkpolicy
kubectl get netpol

使用场景:

  • 排查网络不通问题
  • 验证 Service 访问
  • 测试跨节点网络
  • 网络策略调试

九、资源配额与限制

9.1 查看资源使用

# 查看节点资源使用
kubectl top node

# 查看 Pod 资源使用
kubectl top pod

# 查看 Pod 资源使用(指定命名空间)
kubectl top pod -n <namespace>

# 查看 Pod 资源使用(所有命名空间)
kubectl top pod --all-namespaces

# 查看资源配额
kubectl get resourcequota
kubectl get quota

# 查看限制范围
kubectl get limitrange
kubectl get limits

使用场景:

  • 监控资源使用情况
  • 排查资源不足问题
  • 优化资源配置
  • 容量规划

9.2 设置资源配额

# 创建资源配额
kubectl create quota <quota-name> --hard=cpu=2,memory=4Gi,pods=10

# 查看资源配额详情
kubectl describe quota <quota-name>

# 编辑资源配额
kubectl edit quota <quota-name>

# 删除资源配额
kubectl delete quota <quota-name>

使用场景:

  • 限制命名空间资源使用
  • 防止资源过度使用
  • 多团队资源分配
  • 成本控制

十、安全与权限

10.1 RBAC 管理

# 查看 Role
kubectl get roles

# 查看 RoleBinding
kubectl get rolebindings

# 查看 ClusterRole
kubectl get clusterroles

# 查看 ClusterRoleBinding
kubectl get clusterrolebindings

# 创建 Role
kubectl create role <role-name> --verb=get,list,watch --resource=pods

# 创建 RoleBinding
kubectl create rolebinding <rolebinding-name> --role=<role-name> --user=<username>

# 创建 ClusterRole
kubectl create clusterrole <clusterrole-name> --verb=get,list,watch --resource=pods

# 创建 ClusterRoleBinding
kubectl create clusterrolebinding <clusterrolebinding-name> --clusterrole=<clusterrole-name> --user=<username>

使用场景:

  • 配置用户权限
  • 服务账号授权
  • 最小权限原则
  • 多租户隔离

10.2 服务账号管理

# 查看服务账号
kubectl get serviceaccounts
kubectl get sa

# 创建服务账号
kubectl create serviceaccount <serviceaccount-name>

# 删除服务账号
kubectl delete serviceaccount <serviceaccount-name>

# 查看 Token
kubectl describe secret <secret-name>

使用场景:

  • 为 Pod 配置权限
  • CI/CD 流水线访问集群
  • 应用访问 K8s API
  • 自动化脚本认证

十一、配置管理

11.1 ConfigMap 管理

# 创建 ConfigMap(从文件)
kubectl create configmap <configmap-name> --from-file=<file-path>

# 创建 ConfigMap(从目录)
kubectl create configmap <configmap-name> --from-file=<directory-path>

# 创建 ConfigMap(从字面值)
kubectl create configmap <configmap-name> --from-literal=key1=value1 --from-literal=key2=value2

# 查看 ConfigMap
kubectl get configmap <configmap-name> -o yaml

# 编辑 ConfigMap
kubectl edit configmap <configmap-name>

# 删除 ConfigMap
kubectl delete configmap <configmap-name>

# 更新 ConfigMap(不删除 Pod)
kubectl create configmap <configmap-name> --from-file=<file-path> --dry-run=client -o yaml | kubectl apply -f -

使用场景:

  • 管理应用配置文件
  • 环境变量注入
  • 配置热更新
  • 多环境配置管理

11.2 Secret 管理

# 创建 Secret(通用)
kubectl create secret generic <secret-name> --from-literal=key1=value1

# 创建 Secret(TLS)
kubectl create secret tls <secret-name> --cert=<cert-file> --key=<key-file>

# 创建 Secret(Docker Registry)
kubectl create secret docker-registry <secret-name> --docker-server=<server> --docker-username=<username> --docker-password=<password> --docker-email=<email>

# 查看 Secret
kubectl get secret <secret-name> -o yaml

# 解码 Secret
kubectl get secret <secret-name> -o jsonpath='{.data.key1}' | base64 --decode

# 编辑 Secret
kubectl edit secret <secret-name>

# 删除 Secret
kubectl delete secret <secret-name>

使用场景:

  • 存储敏感信息(密码、密钥)
  • TLS 证书管理
  • 镜像拉取认证
  • API 密钥管理

十二、故障排查

12.1 事件查看

# 查看所有事件
kubectl get events

# 查看事件(指定命名空间)
kubectl get events -n <namespace>

# 查看事件(排序)
kubectl get events --sort-by=.metadata.creationTimestamp

# 查看事件(监视模式)
kubectl get events --watch

# 查看事件(宽输出)
kubectl get events -o wide

# 查看特定资源的事件
kubectl describe <resource-type> <resource-name>

使用场景:

  • 排查 Pod 启动失败
  • 查看调度问题
  • 监控集群事件
  • 定位资源冲突

12.2 节点故障排查

# 查看节点状态
kubectl get nodes

# 查看节点详情
kubectl describe node <node-name>

# 查看节点资源使用
kubectl top node

# 标记节点为不可调度
kubectl cordon <node-name>

# 标记节点为可调度
kubectl uncordon <node-name>

# 驱逐节点上的 Pod
kubectl drain <node-name> --ignore-daemonsets --delete-emptydir-data

# 查看节点标签
kubectl get nodes --show-labels

# 给节点添加标签
kubectl label node <node-name> key=value

# 删除节点标签
kubectl label node <node-name> key-

使用场景:

  • 节点维护
  • 排查节点问题
  • 节点升级
  • 资源调度控制

十三、持久化存储

13.1 PV 和 PVC 管理

# 查看 PV
kubectl get pv

# 查看 PVC
kubectl get pvc

# 查看 PV 详情
kubectl describe pv <pv-name>

# 查看 PVC 详情
kubectl describe pvc <pvc-name>

# 删除 PV
kubectl delete pv <pv-name>

# 删除 PVC
kubectl delete pvc <pvc-name>

# 查看 StorageClass
kubectl get storageclass
kubectl get sc

使用场景:

  • 数据持久化
  • 存储容量管理
  • 动态卷供给
  • 存储类选择

13.2 存储调试

# 查看 Pod 挂载信息
kubectl describe pod <pod-name> | grep -A 10 Mounts

# 进入 Pod 查看挂载点
kubectl exec -it <pod-name> -- df -h

# 查看 PVC 绑定状态
kubectl get pvc <pvc-name> -o jsonpath='{.status.phase}'

# 查看 PV 绑定状态
kubectl get pv <pv-name> -o jsonpath='{.status.phase}'

使用场景:

  • 排查存储挂载问题
  • 验证数据持久化
  • 存储容量规划
  • 数据备份恢复

十四、高级操作

14.1 批量操作

# 批量删除 Pod
kubectl delete pods -l app=nginx

# 批量删除所有资源
kubectl delete all --all

# 批量标记节点
kubectl label nodes -l env=prod type=worker

# 批量添加注解
kubectl annotate pods -l app=nginx owner=devops

# 批量导出资源
kubectl get pods -o yaml > all-pods.yaml

使用场景:

  • 批量清理资源
  • 批量标记资源
  • 批量更新配置
  • 资源备份

14.2 资源补丁

# 使用 JSON 补丁
kubectl patch deployment <deployment-name> -p '{"spec":{"replicas":3}}'

# 使用 strategic merge 补丁
kubectl patch deployment <deployment-name> -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","image":"nginx:1.19"}]}}}}'

# 使用 YAML 补丁
kubectl patch deployment <deployment-name> --patch "$(cat patch.yaml)"

# 删除字段
kubectl patch deployment <deployment-name> --type json -p '[{"op": "remove", "path": "/spec/replicas"}]'

使用场景:

  • 精确修改资源字段
  • 自动化脚本更新
  • CI/CD 集成
  • 批量更新

十五、实用技巧

15.1 快捷别名

# 添加到 ~/.bashrc 或 ~/.zshrc
alias k='kubectl'
alias kg='kubectl get'
alias kd='kubectl describe'
alias kl='kubectl logs'
alias ke='kubectl exec -it'
alias ka='kubectl apply -f'
alias kd='kubectl delete -f'
alias kgp='kubectl get pods'
alias kgs='kubectl get svc'
alias kaf='kubectl apply -f'
alias kdf='kubectl delete -f'

# 重新加载配置
source ~/.bashrc

使用场景:

  • 提高命令行效率
  • 减少输入错误
  • 快速执行常用命令

15.2 自动补全

# 启用 kubectl 自动补全(bash)
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc

# 启用 kubectl 自动补全(zsh)
source <(kubectl completion zsh)
echo "if [ $commands[kubectl] ]; then source <(kubectl completion zsh); fi" >> ~/.zshrc

# 为别名也启用补全
complete -o default -F __start_kubectl k

使用场景:

  • 快速输入命令
  • 减少记忆负担
  • 提高效率

15.3 常用组合命令

# 查看所有 Pod 的镜像版本
kubectl get pods -o=jsonpath='{range .items[*]}{"\n"}{.metadata.name}{":\t"}{range .spec.containers[*]}{.image}{", "}{end}{end}'

# 查看所有 Pod 的重启次数
kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.containerStatuses[0].restartCount}{"\n"}{end}'

# 查看 Pod 的资源请求和限制
kubectl get pods -o custom-columns='NAME:metadata.name,CPU_REQ:spec.containers[*].resources.requests.cpu,MEM_REQ:spec.containers[*].resources.requests.memory'

# 批量删除 Evicted Pod
kubectl get pods --all-namespaces --field-selector=status.phase=Failed -o json | kubectl delete -f -

# 查看节点上运行的 Pod
kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node-name>

使用场景:

  • 快速获取信息
  • 批量操作
  • 自动化脚本
  • 监控统计

总结

本文整理了 100+ 条 K8s 常用命令,涵盖了:

  • 集群信息查看
  • 资源管理(创建、删除、更新)
  • 日志查看与调试
  • 滚动更新与回滚
  • 网络调试
  • 资源配额与限制
  • 安全与权限
  • 配置管理
  • 故障排查
  • 持久化存储
  • 高级操作
  • 实用技巧

下一篇预告: K8s 命令实战指南(二)- 生产环境故障排查


参考资料


作者: PaPaBot
发布时间: 2026-03-07
标签: #Kubernetes #K8s #DevOps #运维


本文属于《K8s 命令实战指南》系列文章第一篇

Views: 30

Docker容器化遗留应用(五):综合案例

Docker容器化遗留应用(五):综合案例

Docker容器化

系列导读

这是《Docker容器化遗留应用》系列的最后一篇,前面介绍了容器化理论和实战案例,本篇将通过一个真实的遗留CRM系统容器化案例,展示完整流程。


遗留CRM系统容器化案例

系统架构

原始架构(单体应用):

  • Apache web服务器
  • PHP 7.2后端
  • MySQL 5.7数据库
  • 所有组件耦合在一起

目标:

  • 提升扩展性(应对流量高峰)
  • 提高维护性(独立更新组件)
  • 加快部署效率(从小时到分钟)

步骤一:组件隔离

# docker-compose.yml
version: '3.8'

services:
  # 反向代理
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    networks:
      - crm-network

  # PHP后端
  php:
    build: ./php
    volumes:
      - ./html:/var/www/html
    networks:
      - crm-network

  # 数据库
  database:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
    volumes:
      - mysql-data:/var/lib/mysql
    networks:
      - crm-network

  # 会话管理
  redis:
    image: redis:alpine
    networks:
      - crm-network

networks:
  crm-network:

volumes:
  mysql-data:

步骤二:数据迁移

# 导出现有数据
mysqldump -u root -p crm > crm_backup.sql

# 启动新容器
docker compose up -d

# 导入数据
docker exec -i crm-database-1 mysql -u root -p${DB_PASSWORD} crm < crm_backup.sql

步骤三:测试与部署

# 功能测试
docker run --rm selenium/standalone-chrome python tests/ui_tests.py

# 性能测试
jmeter -n -t crm_load_test.jmx

# 安全测试
docker run --rm owasp/zap2docker-stable zap-baseline.py -t http://crm-app

效果对比:容器化前后

指标 容器化前 容器化后 提升幅度
部署时间 2小时 2分钟 98% ↓
回滚时间 1小时 10秒 99.9% ↓
资源利用率 15% 70% 366% ↑
扩展速度 30分钟/台 5秒/容器 99.7% ↓
环境差异bug 每月3-5个 0 100% ↓

总结:容器化不是万能药,但是良药

获得的好处

  • ✅ 环境一致性:告别"在我机器上能跑"
  • ✅ 快速扩展:应对流量高峰不再是噩梦
  • ✅ 提升部署效率:从小时级到分钟级
  • ✅ 降低运维成本:自动化管理

需要注意

  • ⚠️ 有状态应用(数据库)需要特殊处理
  • ⚠️ 安全配置不能忽视
  • ⚠️ 监控和日志必须跟上
  • ⚠️ 团队需要学习新技术栈

下一步行动

从最简单的Web服务器开始,先在测试环境练手,积累经验后再处理复杂系统。

记住:容器化是一场马拉松,不是百米冲刺。


系列总结

《Docker容器化遗留应用》系列完整内容:

  1. ✅ (一)为什么要容器化 - 理解容器化优势
  2. ✅ (二)容器化三步走 - 掌握基本操作
  3. ✅ (三)网络与数据管理 - 理解核心概念
  4. ✅ (四)实战案例 - 学习真实场景
  5. ✅ (五)综合案例 ← 当前

参考资源


恭喜你完成了整个系列!你的遗留应用已经准备好迎接新生了!

Views: 29

Docker容器化遗留应用(四):实战案例

Docker容器化遗留应用(四):实战案例

Docker容器化

系列导读

这是《Docker容器化遗留应用》系列的第四篇,前几篇介绍了容器化基础,本篇将通过实战案例演示如何容器化真实应用。


案例1:Apache服务器容器化

场景描述

一个运行了5年的Apache服务器,配置复杂,依赖特定版本的PHP模块。需要在不修改代码的情况下容器化。

步骤一:准备工作

mkdir dockerized-apache && cd dockerized-apache

步骤二:编写Dockerfile

FROM ubuntu:20.04

# 避免交互式提示
ENV DEBIAN_FRONTEND=noninteractive

# 安装Apache和PHP
RUN apt-get update && \
    apt-get install -y apache2 php libapache2-mod-php && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 复制配置文件
COPY ./my-httpd.conf /etc/apache2/apache2.conf
COPY ./html/ /var/www/html/

# 暴露端口
EXPOSE 80

# 启动Apache(前台运行)
CMD ["apachectl", "-D", "FOREGROUND"]

步骤三:构建与运行

# 构建镜像
docker build -t dockerized-apache .

# 运行容器
docker run -d -p 8080:80 --name my-apache dockerized-apache

# 测试访问
curl http://localhost:8080

案例2:数据库容器化

开发环境 vs 生产环境

环境 推荐方案 理由
开发 容器化数据库 快速启停,易于重置
测试 容器化数据库 隔离测试数据
生产 托管数据库服务 自动备份、高可用

数据迁移:平滑过渡

# 从现有数据库导出数据
mysqldump -u root -p mydb > backup.sql

# 启动新的MySQL容器
docker run -d --name my-mysql \
  -e MYSQL_ROOT_PASSWORD=mypassword \
  -v mysql-data:/var/lib/mysql \
  mysql:8.0

# 导入数据
docker exec -i my-mysql mysql -u root -pmypassword < backup.sql

配置灵活性

# 开发环境:使用容器化数据库
docker run -d --name dev-db \
  -e MYSQL_ROOT_PASSWORD=dev mysql:8.0

# 生产环境:连接托管数据库
docker run -d --name prod-app \
  -e DB_HOST=my-rds-instance.amazonaws.com \
  -e DB_PASSWORD=${DB_PASSWORD} \
  my-app

配置与环境变量管理

环境变量注入

# 通过-e参数注入
docker run -d --name my-app \
  -e DB_HOST=database.local \
  -e DB_PASSWORD=${DB_PASSWORD} \
  my-application

使用.env文件

# .env文件
DB_HOST=database.local
DB_PASSWORD=supersecret
API_KEY=abc123
# docker-compose.yml
services:
  app:
    image: my-application
    environment:
      - DB_HOST=${DB_HOST}
      - DB_PASSWORD=${DB_PASSWORD}

配置文件挂载

# 挂载主机配置文件
docker run -d --name my-app \
  -v /path/to/config:/app/config:ro \
  my-application

安全提示:敏感信息不要硬编码在Dockerfile中,使用环境变量或密钥管理服务。


安全加固措施

1. 镜像安全

# 使用Docker Scout扫描漏洞
docker scout cves my-legacy-app

# 使用Clair扫描
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \
  arminc/clair-local-scan my-legacy-app

2. 最小权限原则

# 创建非root用户
RUN useradd -m myuser

# 切换到非root用户
USER myuser

# 设置工作目录
WORKDIR /home/myuser

3. 能力限制

# 删除所有能力,仅添加必要的
docker run -d --name my-app \
  --cap-drop=all \
  --cap-add=net_bind_service \
  my-application

4. 只读挂载

# 保护配置文件不被篡改
docker run -d --name my-app \
  -v /path/to/config:/app/config:ro \
  my-application

5. 监控与日志

# 查看容器日志
docker logs -f my-app

# 实时监控资源使用
docker stats my-app

下篇预告

下一篇:《Docker容器化遗留应用(五):综合案例》

将详细介绍:

  • 遗留CRM系统容器化全流程
  • 系统架构拆分
  • 测试与部署
  • 效果对比

系列导航

  • (一)为什么要容器化 - 容器化优势与基本概念
  • (二)容器化三步走 - 从零到一的实践指南
  • (三)网络与数据管理 - 容器间通信与持久化
  • (四)实战案例 ← 当前
  • (五)综合案例 - 遗留CRM系统容器化全流程

通过实战案例,你已经掌握了容器化的核心技术!

Views: 15

Docker容器化遗留应用(三):网络与数据管理

Docker容器化遗留应用(三):网络与数据管理

Docker容器化

系列导读

这是《Docker容器化遗留应用》系列的第三篇,前两篇介绍了容器化优势和基本步骤,本篇将深入讲解网络配置和数据持久化。


网络配置:让容器之间"说得上话"

端口映射:打开对外的窗口

# 将主机的8080端口映射到容器的80端口
docker run -d -p 8080:80 --name web-server nginx

# 访问 http://localhost:8080 即可看到Nginx欢迎页

端口映射格式:主机端口:容器端口

容器间通信:建立内部专线

默认桥接网络

# 启动数据库容器
docker run -d --name my-database mongo

# 应用容器连接数据库
docker run -d --name my-app --link my-database:db my-legacy-app

自定义桥接网络(推荐)

# 创建自定义网络
docker network create crm-network

# 数据库容器加入网络
docker run -d --network=crm-network \
  --name database --network-alias=db mongo

# 应用容器通过别名访问
docker run -d --network=crm-network \
  --name app -e DB_HOST=db my-legacy-app

优势:

  • ✅ 自动DNS解析
  • ✅ 网络隔离
  • ✅ 容器间可通过名称访问

Docker Compose:一键编排多容器

# docker-compose.yml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - DB_HOST=database
    depends_on:
      - database
    networks:
      - crm-network

  database:
    image: mongo:latest
    volumes:
      - mongo-data:/data/db
    networks:
      - crm-network

networks:
  crm-network:
    driver: bridge

volumes:
  mongo-data:

一键启动:

docker compose up -d

数据持久化:别让数据随容器消失

容器是短暂的,删除容器后数据也会消失。对于数据库等有状态应用,必须使用数据卷。

三种卷类型对比

类型 特点 适用场景
匿名卷 随机名称,难管理 临时任务
命名卷 显式创建,易管理 生产环境
主机卷 直接挂载主机目录 开发调试

命名卷:生产环境首选

# 创建命名卷
docker volume create my-mongo-data

# 挂载到容器
docker run -d --name my-mongodb \
  -v my-mongo-data:/data/db \
  mongo

主机卷:开发调试利器

# 挂载主机目录到容器
docker run -d --name my-mongodb \
  -v /path/on/host:/data/db \
  mongo

# 主机上的文件修改会实时同步到容器

Docker Compose卷配置

services:
  database:
    image: mongo
    volumes:
      - mongo-data:/data/db

volumes:
  mongo-data:

运行时自动创建和挂载卷。

数据备份:安全第一

# 从容器复制数据到主机
docker cp my-mongodb:/data/db /backup/mongo-$(date +%Y%m%d)

# 或者使用命名卷备份
docker run --rm -v my-mongo-data:/data -v /backup:/backup \
  busybox tar czf /backup/mongo-$(date +%Y%m%d).tar.gz /data

实战:搭建一个Web应用栈

完整的docker-compose.yml

version: '3.8'

services:
  # 反向代理
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    networks:
      - app-network

  # Web应用
  web:
    build: .
    environment:
      - DB_HOST=database
    depends_on:
      - database
    networks:
      - app-network

  # 数据库
  database:
    image: mysql:5.7
    environment:
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD}
      MYSQL_DATABASE: myapp
    volumes:
      - mysql-data:/var/lib/mysql
    networks:
      - app-network

networks:
  app-network:
    driver: bridge

volumes:
  mysql-data:

一键启动

# 启动所有服务
docker compose up -d

# 查看服务状态
docker compose ps

# 查看日志
docker compose logs -f

# 停止所有服务
docker compose down

下篇预告

下一篇:《Docker容器化遗留应用(四):实战案例》

将详细介绍:

  • Apache服务器容器化
  • 数据库容器化考量
  • 配置与环境变量管理
  • 安全加固措施

系列导航

  • (一)为什么要容器化 - 容器化优势与基本概念
  • (二)容器化三步走 - 从零到一的实践指南
  • (三)网络与数据管理 ← 当前
  • (四)实战案例 - Apache与数据库容器化
  • (五)综合案例 - 遗留CRM系统容器化全流程

掌握了网络和数据管理,你的容器化应用就可以投入生产了!

Views: 25

Docker容器化遗留应用(二):容器化三步走

Docker容器化遗留应用(二):容器化三步走

Docker容器化

系列导读

这是《Docker容器化遗留应用》系列的第二篇,上一篇介绍了容器化的优势,本篇将手把手教你完成容器化的三个基本步骤。


第一步:环境准备(5分钟)

安装Docker

# 一键安装(Ubuntu/Debian)
curl -fsSL https://get.docker.com | bash

# 验证安装
docker --version
# Docker version 24.0.7, build afdd53b

# Docker Compose已内置
docker compose version
# Docker Compose version v2.23.0

国内镜像加速配置(重要!)

国内访问Docker Hub速度较慢,必须配置镜像加速器。

可用的国内镜像源

镜像源 地址 推荐指数
阿里云 https://xxx.mirror.aliyuncs.com ⭐⭐⭐⭐⭐
中科大 https://docker.mirrors.ustc.edu.cn ⭐⭐⭐⭐
网易 https://hub-mirror.c.163.com ⭐⭐⭐

配置方法

# 创建配置文件
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": [
    "https://docker.mirrors.ustc.edu.cn",
    "https://hub-mirror.c.163.com"
  ]
}
EOF

# 重启Docker
sudo systemctl daemon-reload
sudo systemctl restart docker

# 验证
docker info | grep "Registry Mirrors" -A 1

阿里云专属加速器

  1. 访问 阿里云容器镜像服务
  2. 获取专属加速器地址(格式:https://xxx.mirror.aliyuncs.com)
  3. 添加到 daemon.json 的 registry-mirrors 数组

第二步:编写Dockerfile(10分钟)

完整示例(Python Flask)

# 选择轻量级基础镜像
FROM python:3.11-slim

# 设置工作目录
WORKDIR /app

# 先复制依赖文件(利用缓存)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制应用代码
COPY . .

# 暴露端口
EXPOSE 5000

# 启动命令
CMD ["python", "app.py"]

关键指令

指令 说明 示例
FROM 基础镜像 FROM python:3.11-slim
WORKDIR 工作目录 WORKDIR /app
COPY 复制文件 COPY . .
RUN 执行命令 RUN pip install flask
EXPOSE 暴露端口 EXPOSE 5000
CMD 启动命令 CMD ["python", "app.py"]

优化技巧:利用Docker缓存

错误做法(每次都重新安装依赖):

COPY . .
RUN pip install -r requirements.txt

正确做法(代码修改不重新安装):

COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

第三步:构建与运行(1分钟)

构建镜像

# 构建镜像
docker build -t my-legacy-app:v1.0 .

# 查看镜像
docker images | grep my-legacy-app

运行容器

# 运行容器(-d 后台,-p 端口映射)
docker run -d -p 5000:5000 --name my-app my-legacy-app:v1.0

# 查看状态
docker ps

# 查看日志
docker logs -f my-app

测试访问

curl http://localhost:5000

常用命令速查

操作 命令
构建镜像 docker build -t 镜像名:标签 .
运行容器 docker run -d -p 端口:端口 --name 容器名 镜像名
查看容器 docker ps
查看日志 docker logs -f 容器名
停止容器 docker stop 容器名
进入容器 docker exec -it 容器名 /bin/bash

下篇预告

下一篇:《Docker容器化遗留应用(三):网络与数据管理》

将介绍:

  • 端口映射与容器间通信
  • Docker Compose一键编排
  • 数据持久化与卷管理

系列导航

  • (一)为什么要容器化 - 容器化优势与基本概念
  • (二)容器化三步走 ← 当前
  • (三)网络与数据管理 - 容器间通信与持久化
  • (四)实战案例 - Apache与数据库容器化
  • (五)综合案例 - 遗留CRM系统容器化全流程

三步完成,你的第一个容器化应用已经运行起来了!

Views: 19

Docker容器化遗留应用(一):为什么要容器化

Docker容器化遗留应用(一):为什么要容器化

Docker容器化

系列导读

这是《Docker容器化遗留应用》系列的第一篇,整个系列包括:

  1. (一)为什么要容器化 - 容器化优势与基本概念
  2. (二)容器化三步走 - 从零到一的实践指南
  3. (三)网络与数据管理 - 容器间通信与持久化
  4. (四)实战案例 - Apache与数据库容器化
  5. (五)综合案例 - 遗留CRM系统容器化全流程

你的遗留应用还在裸奔吗?

还记得那些跑在物理机上的老系统吗?每次部署都像拆盲盒——"在我机器上能跑"成了开发者的经典借口。环境配置不一致、依赖冲突、扩展困难,这些问题像幽灵一样缠绕着运维团队。

容器化不是什么黑科技,它就是给你的应用穿上统一的"防护服"。


容器化带来的三大改变

1. 环境一致性:告别"在我机器上能跑"

容器将应用及其所有依赖打包在一起,确保开发、测试、生产环境完全一致。

传统部署:

  • 开发环境:Python 3.11 + Flask 2.0
  • 测试环境:Python 3.9 + Flask 1.1
  • 生产环境:Python 3.10 + Flask 2.1
  • 结果:各种奇怪的bug,浪费大量调试时间

容器化部署:

  • 所有环境:同一个镜像,完全一致
  • 结果:开发环境能跑,生产环境也能跑

2. 水平扩展能力:应对流量高峰

通过增加或减少容器数量实现应用水平扩展,结合Kubernetes等编排工具能优化资源分配。

扩展速度对比:

方式 扩展时间 操作复杂度
传统虚拟机 30-60分钟 需要配置新机器
容器 5-10秒 一条命令

真实场景:

  • 双11流量高峰:几秒钟启动100个新容器
  • 流量回落后:自动销毁多余容器,节省资源

3. 部署与回滚效率:快速迭代

容器化部署速度快,出现问题时回滚也迅速。

部署效率对比:

操作 传统部署 容器化部署
部署时间 2小时 2分钟
回滚时间 1小时 10秒
失败率 15% 2%

效果对比:容器化前后的世界

指标 容器化前 容器化后 提升幅度
部署时间 2小时 2分钟 98% ↓
回滚时间 1小时 10秒 99.9% ↓
资源利用率 15% 70% 366% ↑
扩展速度 30分钟/台 5秒/容器 99.7% ↓
环境差异导致的bug 每月3-5个 0 100% ↓

容器化适合哪些遗留应用?

✅ 适合容器化的场景

  • Web应用:Apache、Nginx、Tomcat等
  • API服务:RESTful API、微服务
  • 批处理任务:定时任务、数据处理
  • 数据库:MySQL、PostgreSQL、MongoDB(需注意持久化)

⚠️ 需要谨慎的场景

  • 有状态应用:数据库需要特殊处理
  • 高性能计算:可能需要直接访问硬件
  • Windows应用:需要Windows容器支持

容器化不是万能药

虽然容器化有很多优势,但也需要注意:

优点:

  • ✅ 环境一致性
  • ✅ 快速部署和回滚
  • ✅ 高效资源利用
  • ✅ 便于扩展

挑战:

  • ⚠️ 需要学习新技术栈
  • ⚠️ 有状态应用需要特殊处理
  • ⚠️ 监控和日志需要重新设计
  • ⚠️ 安全配置不能忽视

下篇预告

下一篇:《Docker容器化遗留应用(二):容器化三步走》

将详细介绍:

  • 环境准备(5分钟)
  • 国内镜像加速配置(重要!)
  • 编写Dockerfile(10分钟)
  • 构建与运行容器(1分钟)

系列导航

  • (一)为什么要容器化 ← 当前
  • (二)容器化三步走 - 从零到一的实践指南
  • (三)网络与数据管理 - 容器间通信与持久化
  • (四)实战案例 - Apache与数据库容器化
  • (五)综合案例 - 遗留CRM系统容器化全流程

你的遗留应用还在等什么?开始容器化之旅吧!

Views: 17

08. TypeScript进阶:接口、泛型与类型体操

TypeScript 进阶:接口、泛型与类型体操

TypeScript Advanced

上一期我们学习了 TypeScript 的基础类型。这一期,我们深入接口、泛型和高级类型系统——这些是 TypeScript 真正强大的地方。

接口(Interface)

接口定义了对象的形状。

基本用法

interface User {
  id: number
  name: string
  email: string
}

function printUser(user: User) {
  console.log(`${user.name} `)
}

printUser({
  id: 1,
  name: "Alice",
  email: "alice@example.com"
})

可选属性

interface User {
  id: number
  name: string
  email?: string  // 可选
}

let user1: User = { id: 1, name: "Alice" }
let user2: User = { id: 2, name: "Bob", email: "bob@example.com" }

只读属性

interface User {
  readonly id: number
  name: string
}

let user: User = { id: 1, name: "Alice" }
user.id = 2  // Error: Cannot assign to 'id' because it is read-only

函数类型

interface SearchFunc {
  (source: string, subString: string): boolean
}

let mySearch: SearchFunc = (source, sub) => {
  return source.search(sub) !== -1
}

可索引类型

interface StringArray {
  [index: number]: string
}

let myArray: StringArray = ["Bob", "Fred"]
let myStr: string = myArray[0]

类类型

interface ClockInterface {
  currentTime: Date
  setTime(d: Date): void
}

class Clock implements ClockInterface {
  currentTime: Date = new Date()
  
  setTime(d: Date) {
    this.currentTime = d
  }
  
  constructor(h: number, m: number) {}
}

继承接口

interface Shape {
  color: string
}

interface Square extends Shape {
  sideLength: number
}

let square: Square = {
  color: "blue",
  sideLength: 10
}

多继承:

interface Shape {
  color: string
}

interface PenStroke {
  penWidth: number
}

interface Square extends Shape, PenStroke {
  sideLength: number
}

泛型(Generics)

泛型让我们可以编写可重用的组件。

基本泛型

function identity(arg: T): T {
  return arg
}

let output1 = identity("myString")  // 类型为 string
let output2 = identity(123)  // 类型推断为 number

泛型变量

function loggingIdentity(arg: T[]): T[] {
  console.log(arg.length)
  return arg
}

泛型类型

let myIdentity: (arg: T) => T = identity

// 对象字面量形式
let myIdentity2: { (arg: T): T } = identity

泛型接口

interface GenericIdentityFn {
  (arg: T): T
}

function identity(arg: T): T {
  return arg
}

let myIdentity: GenericIdentityFn = identity

把泛型参数移到接口:

interface GenericIdentityFn {
  (arg: T): T
}

function identity(arg: T): T {
  return arg
}

let myIdentity: GenericIdentityFn = identity

泛型类

class GenericNumber {
  zeroValue: T
  add: (x: T, y: T) => T
}

let myGenericNumber = new GenericNumber()
myGenericNumber.zeroValue = 0
myGenericNumber.add = (x, y) => x + y

泛型约束

interface Lengthwise {
  length: number
}

function loggingIdentity(arg: T): T {
  console.log(arg.length)  // 现在可以访问 .length
  return arg
}

loggingIdentity("hello")  // OK
loggingIdentity([1, 2, 3])  // OK
loggingIdentity(123)  // Error

在泛型中使用类类型

function create(c: { new(): T }): T {
  return new c()
}

class BeeKeeper {
  hasMask: boolean = true
}

class ZooKeeper {
  nametag: string = "Mikle"
}

class Animal {
  numLegs: number = 4
}

class Bee extends Animal {
  keeper: BeeKeeper = new BeeKeeper()
}

class Lion extends Animal {
  keeper: ZooKeeper = new ZooKeeper()
}

function createInstance<A>(c: new () => A): A {
  return new c()
}

createInstance(Lion).keeper.nametag
createInstance(Bee).keeper.hasMask

高级类型

交叉类型

将多个类型合并为一个。

interface Person {
  name: string
}

interface Loggable {
  log(): void
}

type PersonLoggable = Person & Loggable

const person: PersonLoggable = {
  name: "Alice",
  log() {
    console.log(this.name)
  }
}

联合类型

type StringOrNumber = string | number

function add(a: StringOrNumber, b: StringOrNumber) {
  if (typeof a === "string" || typeof b === "string") {
    return a.toString() + b.toString()
  }
  return a + b
}

类型保护

interface Fish {
  swim(): void
}

interface Bird {
  fly(): void
}

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined
}

function move(pet: Fish | Bird) {
  if (isFish(pet)) {
    pet.swim()
  } else {
    pet.fly()
  }
}

typeof 类型保护

function padLeft(value: string, padding: string | number) {
  if (typeof padding === "number") {
    return Array(padding + 1).join(" ") + value
  }
  if (typeof padding === "string") {
    return padding + value
  }
  throw new Error(`Expected string or number, got '${padding}'.`)
}

instanceof 类型保护

class Dog {
  bark() {}
}

class Cat {
  meow() {}
}

function speak(pet: Dog | Cat) {
  if (pet instanceof Dog) {
    pet.bark()
  } else {
    pet.meow()
  }
}

null 检查

function f(str: string | null) {
  if (str === null) {
    return "default"
  }
  return str.toUpperCase()
}

可选链:

let x = foo?.bar.baz()
// 等价于
let x = foo === null || foo === undefined ? undefined : foo.bar.baz()

空值合并:

let x = foo ?? "default"
// 等价于
let x = foo !== null && foo !== undefined ? foo : "default"

类型推断

基础推断

let x = 3  // 推断为 number
let y = [0, 1, null]  // 推断为 (number | null)[]

上下文推断

window.onmousedown = function(mouseEvent) {
  console.log(mouseEvent.button)  // 推断为 MouseEvent
}

类型推断方向

// 从右向左
let x = 3

// 从左向右(上下文类型)
window.onmousedown = function(mouseEvent) {
  return mouseEvent.button
}

映射类型

从旧类型创建新类型。

Partial

所有属性变为可选。

type Partial = {
  [P in keyof T]?: T[P]
}

interface User {
  id: number
  name: string
}

type PartialUser = Partial
// { id?: number; name?: string; }

Required

所有属性变为必选。

type Required = {
  [P in keyof T]-?: T[P]
}

Readonly

所有属性变为只读。

type Readonly = {
  readonly [P in keyof T]: T[P]
}

Pick

选取部分属性。

type Pick = {
  [P in K]: T[P]
}

interface User {
  id: number
  name: string
  email: string
}

type UserPreview = Pick
// { id: number; name: string; }

Omit

排除部分属性。

type Omit = Pick<T, Exclude>

type UserWithoutEmail = Omit
// { id: number; name: string; }

Record

创建对象类型。

type Record = {
  [P in K]: T
}

type UserMap = Record

条件类型

根据条件选择类型。

type ReturnType = T extends (...args: any[]) => infer R ? R : any

function foo(): number {
  return 1
}

type R = ReturnType  // number

实战示例

API 响应类型

interface ApiResponse {
  code: number
  message: string
  data: T
}

interface User {
  id: number
  name: string
}

async function fetchUser(id: number): Promise<ApiResponse> {
  const response = await fetch(`/api/users/${id}`)
  return response.json()
}

// 使用
const result = await fetchUser(1)
console.log(result.data.name)

事件处理

interface EventHandler {
  (event: T): void
}

interface ClickEvent {
  type: "click"
  x: number
  y: number
}

const handler: EventHandler = (event) => {
  console.log(`Clicked at ${event.x}, ${event.y}`)
}

状态管理

type State = {
  user: User | null
  loading: boolean
  error: string | null
}

type Action =
  | { type: "FETCH_START" }
  | { type: "FETCH_SUCCESS"; payload: User }
  | { type: "FETCH_ERROR"; payload: string }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "FETCH_START":
      return { ...state, loading: true }
    case "FETCH_SUCCESS":
      return { ...state, loading: false, user: action.payload }
    case "FETCH_ERROR":
      return { ...state, loading: false, error: action.payload }
  }
}

总结

TypeScript 的高级特性:

  • 接口:定义对象形状
  • 泛型:创建可重用组件
  • 类型保护:缩小类型范围
  • 映射类型:从旧类型创建新类型
  • 条件类型:根据条件选择类型

下一期,我们学习 TypeScript 的项目配置和最佳实践。


进阶资源:

Views: 37

10. Vue3 + TypeScript:完整集成指南

Vue3 + TypeScript:完整集成指南

Vue3 TypeScript

恭喜你走到最后一期!前面我们学习了 ES6、Vite、Vue3 基础、组合式 API 和 TypeScript。现在,让我们把 TypeScript 完整集成到 Vue3 项目中。

项目创建

Vite + Vue + TypeScript

npm create vite@latest my-vue-app -- --template vue-ts
cd my-vue-app
npm install

项目结构

src/
├── main.ts
├── App.vue
├── vite-env.d.ts
├── components/
│   └── HelloWorld.vue
├── views/
├── router/
│   └── index.ts
├── stores/
│   └── user.ts
├── types/
│   └── index.ts
├── api/
│   └── user.ts
├── composables/
│   └── useUser.ts
└── utils/
    └── format.ts

类型定义

全局类型

// types/index.ts
export interface User {
  id: number
  name: string
  email: string
  avatar?: string
}

export interface ApiResponse {
  code: number
  message: string
  data: T
}

export type Theme = 'light' | 'dark'

export interface AppState {
  user: User | null
  theme: Theme
  loading: boolean
}

组件 Props 类型


interface Props {
  title: string
  count?: number
  users: User[]
}

const props = withDefaults(defineProps(), {
  count: 0
})

组件 Emits 类型


interface Emits {
  (e: 'update', value: string): void
  (e: 'delete', id: number): void
  (e: 'change', event: Event): void
}

const emit = defineEmits()

function handleUpdate() {
  emit('update', 'new value')
}

组合式 API + TypeScript

ref

import { ref } from 'vue'

// 类型推断
const count = ref(0)
const name = ref('Alice')

// 显式类型
const user = ref(null)
const items = ref([])

reactive

import { reactive } from 'vue'

interface State {
  count: number
  name: string
  items: string[]
}

const state = reactive({
  count: 0,
  name: '',
  items: []
})

computed

import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

// 自动推断返回类型
const fullName = computed(() => <code>${firstName.value} ${lastName.value})

// 显式类型
const userCount = computed(() => users.value.length)

组合式函数

// composables/useUser.ts
import { ref, computed } from 'vue'
import type { User } from '@/types'

export function useUser() {
  const user = ref(null)
  const loading = ref(false)
  const error = ref(null)

  const isLoggedIn = computed(() => !!user.value)
  const userName = computed(() => user.value?.name ?? 'Guest')

  async function fetchUser(id: number) {
    loading.value = true
    error.value = null

    try {
      const response = await fetch(<code>/api/users/${id})
      user.value = await response.json()
    } catch (e) {
      error.value = e instanceof Error ? e.message : 'Unknown error'
    } finally {
      loading.value = false
    }
  }

  function logout() {
    user.value = null
  }

  return {
    user,
    loading,
    error,
    isLoggedIn,
    userName,
    fetchUser,
    logout
  }
}

Pinia + TypeScript

Store 类型定义

// stores/user.ts
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types'

export const useUserStore = defineStore('user', () => {
  // State
  const user = ref(null)
  const token = ref(localStorage.getItem('token'))

  // Getters
  const isLoggedIn = computed(() => !!token.value)
  const userName = computed(() => user.value?.name ?? 'Guest')

  // Actions
  async function login(email: string, password: string) {
    const response = await fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password })
    })

    const data = await response.json()
    user.value = data.user
    token.value = data.token
    localStorage.setItem('token', data.token)
  }

  function logout() {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
  }

  return {
    user,
    token,
    isLoggedIn,
    userName,
    login,
    logout
  }
}, {
  persist: true
})

使用 Store


import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'

const userStore = useUserStore()

// 解构(保持响应性)
const { user, isLoggedIn, userName } = storeToRefs(userStore)

// Actions
const { login, logout } = userStore

// 表单
const email = ref('')
const password = ref('')

async function handleLogin() {
  await login(email.value, password.value)
}

  <div>
    <p>Welcome, {{ userName }}</p>
    <button>Logout</button>
  </div>

    <button type="submit">Login</button>

Vue Router + TypeScript

路由类型

// router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/users/:id',
    name: 'User',
    component: () => import('@/views/User.vue'),
    props: true,
    meta: {
      requiresAuth: true
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

export default router

路由元信息类型

// types/router.ts
import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    requiresAuth?: boolean
    title?: string
    roles?: string[]
  }
}

使用路由


import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

// 获取参数(类型安全)
const userId = computed(() => Number(route.params.id))

// 编程式导航
function goToUser(id: number) {
  router.push({ name: 'User', params: { id } })
}

API 集成

类型安全的 API 客户端

// api/client.ts
import type { ApiResponse } from '@/types'

class ApiClient {
  private baseUrl: string

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl
  }

  private async request(
    path: string,
    options?: RequestInit
  ): Promise {
    const response = await fetch(<code>${this.baseUrl}${path}, {
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...options?.headers
      }
    })

    if (!response.ok) {
      throw new Error(HTTP error! status: ${response.status})
    }

    return response.json()
  }

  get(path: string): Promise {
    return this.request(path)
  }

  post(path: string, data: unknown): Promise {
    return this.request(path, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  put(path: string, data: unknown): Promise {
    return this.request(path, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }

  delete(path: string): Promise {
    return this.request(path, {
      method: 'DELETE'
    })
  }
}

export const api = new ApiClient('/api')

API 模块

// api/user.ts
import { api } from './client'
import type { User, ApiResponse } from '@/types'

export const userApi = {
  getAll(): Promise {
    return api.get<ApiResponse>('/users').then(r => r.data)
  },

  getById(id: number): Promise {
    return api.get<ApiResponse>(<code>/users/${id}).then(r => r.data)
  },

  create(data: Omit): Promise {
    return api.post<ApiResponse>('/users', data).then(r => r.data)
  },

  update(id: number, data: Partial): Promise {
    return api.put<ApiResponse>(/users/${id}, data).then(r => r.data)
  },

  delete(id: number): Promise {
    return api.delete(/users/${id})
  }
}

使用 API


import { ref, onMounted } from 'vue'
import { userApi } from '@/api/user'
import type { User } from '@/types'

const users = ref([])
const loading = ref(false)
const error = ref(null)

async function fetchUsers() {
  loading.value = true
  error.value = null

  try {
    users.value = await userApi.getAll()
  } catch (e) {
    error.value = e instanceof Error ? e.message : 'Unknown error'
  } finally {
    loading.value = false
  }
}

onMounted(fetchUsers)

  <div>Loading...</div>
  <div>{{ error }}</div>
  <ul>
    <li>
      {{ user.name }}
    </li>
  </ul>

表单处理

类型安全的表单


import { ref, reactive } from 'vue'

interface FormData {
  name: string
  email: string
  age: number
  subscribe: boolean
}

interface FormErrors {
  name?: string
  email?: string
  age?: string
}

const form = reactive({
  name: '',
  email: '',
  age: 0,
  subscribe: false
})

const errors = reactive({})

function validate(): boolean {
  let isValid = true

  if (!form.name.trim()) {
    errors.name = 'Name is required'
    isValid = false
  }

  if (!form.email.includes('@')) {
    errors.email = 'Invalid email'
    isValid = false
  }

  if (form.age  150) {
    errors.age = 'Invalid age'
    isValid = false
  }

  return isValid
}

async function handleSubmit() {
  if (!validate()) return

  // 提交表单
  await submitForm(form)
}

    <div>

      <span>{{ errors.name }}</span>
    </div>

    <div>

      <span>{{ errors.email }}</span>
    </div>

    <div>

      <span>{{ errors.age }}</span>
    </div>

    <div>
      <label>

        Subscribe to newsletter
      </label>
    </div>

    <button type="submit">Submit</button>

使用 vee-validate

npm install vee-validate zod @vee-validate/zod

import { useForm, useField } from 'vee-validate'
import { z } from 'zod'
import { toTypedSchema } from '@vee-validate/zod'

const schema = toTypedSchema(
  z.object({
    name: z.string().min(1, 'Name is required'),
    email: z.string().email('Invalid email'),
    age: z.number().min(0).max(150)
  })
)

const { handleSubmit, errors } = useForm({
  validationSchema: schema
})

const { value: name } = useField('name')
const { value: email } = useField('email')
const { value: age } = useField('age')

const onSubmit = handleSubmit((values) => {
  console.log(values)
})

工具类型

组件实例类型

import type { ComponentInstance } from 'vue'

// 获取组件实例类型
type MyComponentInstance = ComponentInstance

提取 Props 类型

import type { ExtractPropTypes } from 'vue'

const propsDefinition = {
  title: String,
  count: {
    type: Number,
    default: 0
  }
} as const

type Props = ExtractPropTypes
// { title: string; count: number }

组件自定义类型

// 自定义组件类型
declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    MyButton: typeof import('@/components/MyButton.vue')['default']
    MyInput: typeof import('@/components/MyInput.vue')['default']
  }
}

测试

Vitest 配置

// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    environment: 'jsdom',
    globals: true
  }
})

组件测试

// components/__tests__/Button.spec.ts
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import Button from '../Button.vue'

describe('Button', () => {
  it('renders with text', () => {
    const wrapper = mount(Button, {
      props: { text: 'Click me' }
    })
    expect(wrapper.text()).toBe('Click me')
  })

  it('emits click event', async () => {
    const wrapper = mount(Button, {
      props: { text: 'Click me' }
    })
    await wrapper.trigger('click')
    expect(wrapper.emitted('click')).toBeTruthy()
  })
})

最佳实践

1. 使用 script setup


// 推荐

2. 类型优先

// 先定义类型,再实现
interface User {
  id: number
  name: string
}

const user = ref(null)

3. 使用组合式函数

// 提取可复用逻辑
export function useUser() {
  // ...
}

4. 严格模式

// tsconfig.json
{
  "compilerOptions": {
    "strict": true
  }
}

5. 类型安全的 Props


interface Props {
  title: string
  count?: number
}

const props = withDefaults(defineProps(), {
  count: 0
})

系列总结

恭喜你完成了从 ES6 到 Vue3 + TypeScript 的完整学习之旅!

第一期:TypeScript 基础类型系统
第二期:接口、泛型与类型体操
第三期:项目配置与最佳实践
第四期:TypeScript 与前端框架
第五期:Vue3 + TypeScript 完整集成

你现在掌握了:

  • TypeScript 类型系统
  • Vue3 组合式 API
  • 类型安全的组件开发
  • Pinia 状态管理
  • Vue Router 类型安全
  • API 集成最佳实践

下一步:

  • 学习 Nuxt 3(Vue3 全栈框架)
  • 探索 Vite 插件开发
  • 学习服务端渲染
  • 阅读官方文档

进阶资源:


恭喜!你已经掌握了 Vue3 + TypeScript 的核心技能。去构建你的下一个项目吧!

Views: 22

09. TypeScript与前端框架:React、Node.js

TypeScript 与前端框架:React、Node.js

TypeScript Frameworks

TypeScript 与现代前端框架是天生一对。这一期,我们学习 TypeScript 在 React 和 Node.js 中的应用。

React + TypeScript

创建项目

# Vite(推荐)
npm create vite@latest my-app -- --template react-ts

# Create React App
npx create-react-app my-app --template typescript

# Next.js
npx create-next-app@latest my-app --typescript

组件类型

函数组件

// 简单组件
const Button: React.FC = () => {
  return <button>Click me</button>
}

// 带 Props 的组件
interface ButtonProps {
  text: string
  onClick: () => void
  disabled?: boolean
}

const Button: React.FC = ({ 
  text, 
  onClick, 
  disabled = false 
}) => {
  return (
    <button disabled="{disabled}">
      {text}
    </button>
  )
}

内联 Props

type UserCardProps = {
  name: string
  email: string
  avatar?: string
}

function UserCard({ name, email, avatar }: UserCardProps) {
  return (
    <div>
      {avatar && <img src="{avatar}" alt="{name}" />}
      <h3>{name}</h3>
      <p>{email}</p>
    </div>
  )
}

Hooks 类型

useState

// 类型推断
const [count, setCount] = useState(0)

// 显式类型
const [user, setUser] = useState(null)

// 复杂类型
const [items, setItems] = useState([])

useEffect

useEffect(() => {
  // 副作用逻辑
  return () => {
    // 清理函数
  }
}, [dependency])

useRef

// DOM 引用
const inputRef = useRef(null)

// 任意值引用
const timerRef = useRef(null)

useContext

interface ThemeContextType {
  theme: 'light' | 'dark'
  toggleTheme: () => void
}

const ThemeContext = createContext(null)

function useTheme() {
  const context = useContext(ThemeContext)
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider')
  }
  return context
}

useReducer

type State = {
  count: number
}

type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'reset'; payload: number }

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 }
    case 'decrement':
      return { count: state.count - 1 }
    case 'reset':
      return { count: action.payload }
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0 })

事件类型

function Form() {
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
  }

  const handleChange = (e: React.ChangeEvent) => {
    console.log(e.target.value)
  }

  const handleClick = (e: React.MouseEvent) => {
    console.log('clicked')
  }

  return (

      <button>Submit</button>

  )
}

泛型组件

interface ListProps {
  items: T[]
  renderItem: (item: T) => React.ReactNode
}

function List({ items, renderItem }: ListProps) {
  return (
    <ul>
      {items.map((item, index) => (
        <li>{renderItem(item)}</li>
      ))}
    </ul>
  )
}

// 使用
 <span>{user.name}</span>}
/>

高阶组件

interface WithLoadingProps {
  loading?: boolean
}

function withLoading<P>(
  Component: React.ComponentType<P>
): React.FC<P> {
  return ({ loading, ...props }) => {
    if (loading) {
      return <div>Loading...</div>
    }
    return 
  }
}

Node.js + TypeScript

项目设置

mkdir my-project
cd my-project
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Express 示例

npm install express
npm install @types/express --save-dev
import express, { Request, Response, NextFunction } from 'express'

const app = express()
app.use(express.json())

// 类型定义
interface User {
  id: number
  name: string
  email: string
}

// 内存数据库
const users: User[] = []

// 路由
app.get('/users', (req: Request, res: Response) => {
  res.json(users)
})

app.get('/users/:id', (req: Request, res: Response) => {
  const user = users.find(u => u.id === parseInt(req.params.id))
  if (!user) {
    res.status(404).send('User not found')
    return
  }
  res.json(user)
})

app.post('/users', (req: Request<{}, User, Omit>, res: Response) => {
  const newUser: User = {
    id: users.length + 1,
    ...req.body
  }
  users.push(newUser)
  res.status(201).json(newUser)
})

// 错误处理
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack)
  res.status(500).json({ error: err.message })
})

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})

中间件类型

interface AuthRequest extends Request {
  user?: {
    id: number
    role: string
  }
}

function authMiddleware(
  req: AuthRequest,
  res: Response,
  next: NextFunction
) {
  const token = req.headers.authorization
  if (!token) {
    res.status(401).json({ error: 'Unauthorized' })
    return
  }

  // 验证 token...
  req.user = { id: 1, role: 'admin' }
  next()
}

app.get('/protected', authMiddleware, (req: AuthRequest, res: Response) => {
  res.json({ user: req.user })
})

数据库集成

// Prisma 示例
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function getUsers() {
  const users = await prisma.user.findMany({
    include: { posts: true }
  })
  return users
}

async function createUser(data: { name: string; email: string }) {
  const user = await prisma.user.create({
    data
  })
  return user
}

工具函数

API 客户端

interface HttpClient {
  get(url: string): Promise
  post(url: string, data: unknown): Promise
  put(url: string, data: unknown): Promise
  delete(url: string): Promise
}

class FetchHttpClient implements HttpClient {
  private baseUrl: string

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl
  }

  async get(url: string): Promise {
    const response = await fetch(<code>${this.baseUrl}${url})
    if (!response.ok) {
      throw new Error(HTTP error! status: ${response.status})
    }
    return response.json()
  }

  async post(url: string, data: unknown): Promise {
    const response = await fetch(${this.baseUrl}${url}, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    })
    return response.json()
  }

  // ... 其他方法
}

状态管理

// 简单的状态管理器
type Listener = (state: T) => void

class Store {
  private state: T
  private listeners: Listener[] = []

  constructor(initialState: T) {
    this.state = initialState
  }

  getState(): T {
    return this.state
  }

  setState(newState: Partial) {
    this.state = { ...this.state, ...newState }
    this.listeners.forEach(listener => listener(this.state))
  }

  subscribe(listener: Listener) {
    this.listeners.push(listener)
    return () => {
      this.listeners = this.listeners.filter(l => l !== listener)
    }
  }
}

// 使用
interface AppState {
  user: User | null
  loading: boolean
}

const store = new Store({
  user: null,
  loading: false
})

测试

Jest 配置

npm install --save-dev jest ts-jest @types/jest
npx ts-jest config:init

单元测试

// math.ts
export function add(a: number, b: number): number {
  return a + b
}

// math.test.ts
import { add } from './math'

describe('add', () => {
  it('should add two numbers', () => {
    expect(add(1, 2)).toBe(3)
  })
})

React 组件测试

// Button.tsx
interface ButtonProps {
  text: string
  onClick: () => void
}

export const Button: React.FC = ({ text, onClick }) => {
  return <button>{text}</button>
}

// Button.test.tsx
import { render, screen, fireEvent } from '@testing-library/react'
import { Button } from './Button'

describe('Button', () => {
  it('should render with text', () => {
    render(<Button> {}} />)
    expect(screen.getByText('Click me')).toBeInTheDocument()
  })

  it('should call onClick when clicked', () => {
    const handleClick = jest.fn()
    render(<Button />)
    fireEvent.click(screen.getByText('Click me'))
    expect(handleClick).toHaveBeenCalledTimes(1)
  })
})

实战技巧

类型安全的 API 路由

// 路由定义
type Route = {
  path: string
  method: 'GET' | 'POST' | 'PUT' | 'DELETE'
  handler: (req: Request, res: Response) => void | Promise
}

const routes: Route[] = [
  {
    path: '/users',
    method: 'GET',
    handler: getUsers
  },
  {
    path: '/users',
    method: 'POST',
    handler: createUser
  }
]

// 自动注册路由
routes.forEach(route => {
  app[route.method.toLowerCase()](route.path, route.handler)
})

类型安全的环境变量

// env.ts
import { z } from 'zod'

const envSchema = z.object({
  NODE_ENV: z.enum(['development', 'production', 'test']),
  PORT: z.string().transform(Number),
  DATABASE_URL: z.string(),
  JWT_SECRET: z.string()
})

export const env = envSchema.parse(process.env)

总结

TypeScript 与框架结合要点:

  • React:组件类型、Hooks 类型、事件类型
  • Node.js:Express 类型、中间件、数据库
  • 测试:Jest + ts-jest
  • 最佳实践:类型安全的 API、环境变量

下一期,我们学习 Vue3 + TypeScript 的完整集成指南。


框架文档:

Views: 9

↓
↑