← 返回首页

Kubernetes入门:从Pod到Service

前言

Kubernetes(K8s)是容器编排的事实标准。本文介绍K8s的核心概念,帮助初学者快速上手。

一、核心概念

1.1 Pod

Pod是K8s中最小的部署单元,包含一个或多个紧密关联的容器:

apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  labels:
    app: nginx
spec:
  containers:
    - name: nginx
      image: nginx:1.25
      ports:
        - containerPort: 80

1.2 Deployment

Deployment管理Pod的副本数量、滚动更新和回滚:

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:1.25
          ports:
            - containerPort: 80
          resources:
            limits:
              memory: "128Mi"
              cpu: "500m"

1.3 Service

Service为一组Pod提供稳定的访问入口和负载均衡:

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  type: ClusterIP
  selector:
    app: nginx
  ports:
    - port: 80
      targetPort: 80

二、Service类型

类型说明使用场景
ClusterIP集群内部访问后端微服务间通信
NodePort通过节点端口暴露开发测试环境
LoadBalancer云厂商负载均衡生产环境对外暴露
ExternalName映射外部服务对接外部API

三、ConfigMap与Secret

3.1 ConfigMap

apiVersion: v1
kind: ConfigMap
metadata:
  name: app-config
data:
  APP_ENV: production
  LOG_LEVEL: info

3.2 Secret

apiVersion: v1
kind: Secret
metadata:
  name: db-secret
type: Opaque
data:
  username: YWRtaW4=     # base64编码
  password: cGFzc3dvcmQ= # base64编码

四、常用kubectl命令

# 查看Pod状态
kubectl get pods -o wide

# 查看Service
kubectl get services

# 查看Deployment
kubectl get deployments

# 查看日志
kubectl logs -f deployment/nginx-deployment

# 进入容器
kubectl exec -it pod/nginx-pod -- /bin/sh

# 扩容
kubectl scale deployment/nginx-deployment --replicas=5

# 滚动更新
kubectl set image deployment/nginx-deployment nginx=nginx:1.26

# 回滚
kubectl rollout undo deployment/nginx-deployment
Kubernetes学习曲线较陡,建议先在本地用minikube或kind搭建练习环境,熟悉核心概念后再上生产。