Skip to content
第 213 / 250 章运维⏱ 16 分钟阅读

第 213 章:Kubernetes 入门

学习目标

  • 理解 K8s 架构
  • 掌握 Pod / Deployment / Service
  • 学会 kubectl 命令
  • 部署第一个应用

一、Kubernetes 简介

K8s 是容器编排的事实标准,自动化部署、扩缩、运维容器化应用。

二、核心概念

2.1 架构组件

Master(控制平面):

  • kube-apiserver:API 入口
  • etcd:集群存储
  • kube-scheduler:调度 Pod
  • kube-controller-manager:控制器

Node(工作节点):

  • kubelet:节点 Agent
  • kube-proxy:网络代理
  • 容器运行时(containerd / Docker)

2.2 工作负载

资源说明
Pod最小调度单元(可含多容器)
Deployment无状态应用
StatefulSet有状态应用
DaemonSet节点级守护
Job / CronJob一次性 / 定时任务

2.3 网络 / 配置

资源说明
Service服务发现 + 负载均衡
IngressHTTP 路由
ConfigMap配置
Secret敏感数据
PersistentVolume存储卷

三、本地集群

3.1 minikube

bash
# 安装
brew install minikube
minikube start

# 状态
minikube status
kubectl get nodes

3.2 kind

bash
brew install kind
kind create cluster

3.3 Docker Desktop

启用 K8s 设置即可。

四、kubectl 命令

4.1 集群信息

bash
kubectl cluster-info
kubectl get nodes
kubectl version

4.2 资源操作

bash
# 查询
kubectl get pods
kubectl get deployments
kubectl get svc
kubectl get all

# 详细
kubectl describe pod mypod

# 日志
kubectl logs mypod
kubectl logs -f mypod                 # 跟踪
kubectl logs mypod -c container1       # 多容器

# 进入
kubectl exec -it mypod -- bash

# 端口转发
kubectl port-forward mypod 8080:3000

# 资源使用
kubectl top node
kubectl top pod

4.3 创建

bash
# 从文件
kubectl apply -f deployment.yaml

# 临时跑
kubectl run nginx --image=nginx --port=80

# 暴露
kubectl expose deployment nginx --port=80 --type=NodePort

4.4 删除

bash
kubectl delete pod mypod
kubectl delete -f deployment.yaml
kubectl delete deployment myapp

4.5 上下文

bash
kubectl config get-contexts
kubectl config use-context minikube

五、YAML 基础

yaml
apiVersion: v1              # 版本
kind: Pod                   # 资源类型
metadata:
  name: mypod
  labels:
    app: myapp
spec:                       # 规格
  containers:
    - name: app
      image: nginx:1.25
      ports:
        - containerPort: 80
      resources:
        requests:
          cpu: 100m
          memory: 128Mi
        limits:
          cpu: 500m
          memory: 256Mi

六、Pod

yaml
apiVersion: v1
kind: Pod
metadata:
  name: mypod
  labels:
    app: myapp
spec:
  containers:
    - name: app
      image: myapp:1.0
      ports:
        - containerPort: 3000
      env:
        - name: DB_HOST
          value: db
      volumeMounts:
        - name: data
          mountPath: /app/data
  volumes:
    - name: data
      emptyDir: {}

七、Deployment

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp
spec:
  replicas: 3                # 副本数
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
        - name: app
          image: myapp:1.0
          ports:
            - containerPort: 3000
          resources:
            requests:
              cpu: 100m
              memory: 128Mi
            limits:
              cpu: 500m
              memory: 512Mi
          readinessProbe:     # 就绪探针
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 10
            periodSeconds: 5
          livenessProbe:      # 存活探针
            httpGet:
              path: /health
              port: 3000
            initialDelaySeconds: 30
            periodSeconds: 10
bash
kubectl apply -f deployment.yaml
kubectl get deployment
kubectl scale deployment myapp --replicas=5

八、Service

yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-svc
spec:
  type: ClusterIP           # 默认,集群内
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 3000

8.1 Service 类型

类型说明
ClusterIP集群内(默认)
NodePort节点端口(30000-32767)
LoadBalancer云厂商 LB
ExternalNameCNAME

8.2 NodePort 示例

yaml
apiVersion: v1
kind: Service
metadata:
  name: myapp-nodeport
spec:
  type: NodePort
  selector:
    app: myapp
  ports:
    - port: 80
      targetPort: 3000
      nodePort: 30080

九、Ingress

bash
# 启用(以 minikube 为例)
minikube addons enable ingress
yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress
spec:
  rules:
    - host: example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: myapp-svc
                port:
                  number: 80

十、ConfigMap & Secret

10.1 ConfigMap

yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  LOG_LEVEL: info
  PORT: "3000"
  config.yaml: |
    key: value
    nested:
      a: 1

使用:

yaml
env:
  - name: LOG_LEVEL
    valueFrom:
      configMapKeyRef:
        name: app-config
        key: LOG_LEVEL

volumeMounts:
  - name: config
    mountPath: /app/config.yaml
    subPath: config.yaml
volumes:
  - name: config
    configMap:
      name: app-config

10.2 Secret

bash
kubectl create secret generic db-pass --from-literal=password=secret123
yaml
apiVersion: v1
kind: Secret
metadata:
  name: db-pass
type: Opaque
stringData:
  password: secret123

使用:

yaml
env:
  - name: DB_PASS
    valueFrom:
      secretKeyRef:
        name: db-pass
        key: password

十一、namespace

bash
kubectl create namespace dev
kubectl get pods -n dev

# 切换
kubectl config set-context --current --namespace=dev
yaml
metadata:
  namespace: dev

十二、调试技巧

bash
# 排错四件套
kubectl get pod mypod -o yaml
kubectl describe pod mypod
kubectl logs mypod
kubectl exec -it mypod -- bash

# 事件
kubectl get events --sort-by=.metadata.creationTimestamp

# 资源使用
kubectl top pod mypod

# 调试镜像
kubectl run debug --image=alpine --rm -it --restart=Never -- sh

十三、本章小结

资源用途
Pod容器组
Deployment无状态副本
Service服务发现
IngressHTTP 路由
ConfigMap配置
Secret密钥

动手练习

  1. 用 minikube 启动本地集群
  2. 部署 nginx Deployment
  3. 暴露 NodePort 服务
  4. 配置 ConfigMap 注入环境变量

推荐阅读


下一章:第 214 章:K8s 进阶与 Helm

本站基于 VitePress 构建 · 由 Codebook 团队维护