Kubernetes 入门部署指南:从零搭建 K8s 集群

Kubernetes(K8s)是容器编排的事实标准,已成为云原生时代的"操作系统"。

一、核心概念

概念 说明
Pod 最小的部署单元,包含一个或多个容器
Service 网络抽象层,提供稳定的访问入口
Deployment 声明式 Pod 管理
Namespace 资源隔离分组
ConfigMap 配置管理
Secret 敏感信息管理

二、本地搭建(Minikube)

# 安装 minikube
brew install minikube

# 启动集群
minikube start --cpus 4 --memory 8192

# 查看状态
kubectl cluster-info
kubectl get nodes

三、部署应用

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:latest
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector:
    app: nginx
  ports:
  - port: 80
    targetPort: 80
  type: NodePort
kubectl apply -f deployment.yaml
kubectl get pods
kubectl get services
minikube service nginx-service

四、常用命令

kubectl get pods                 # 查看 Pod
kubectl get deployments          # 查看 Deployment
kubectl logs pod-name           # 查看日志
kubectl exec -it pod-name -- sh # 进入容器
kubectl describe pod pod-name   # 查看详情
kubectl scale deployment nginx --replicas=5  # 扩缩容

五、生产环境建议

  • 使用托管 K8s 服务(EKS、AKS、GKE)
  • 配置资源请求和限制
  • 设置 HPA 自动伸缩
  • 使用 Helm 管理应用发布