什么是Kubernetes?当今最流行的容器编排平台
DevOps

什么是Kubernetes?当今最流行的容器编排平台

什么是Kubernetes?深入了解当今最强大的容器编排平台:架构、Pod、Deployment、Service、自动扩缩容以及何时应该使用K8s。

系列文章: DevOps
  1. 1 API网关是什么?微服务的统一入口点
  2. 2 NAT是什么?计算机网络中的网络地址转换详解
  3. 3 GitLab CI/CD是什么?自动化构建、测试与部署流水线
  4. 4 Apache Kafka是什么?分布式事件流处理平台详解
  5. 5 Serverless是什么?FaaS、冷启动与何时选择无服务器架构
  6. 6 Subnet和CIDR是什么?IP网络分段与现代路由
  7. 7 什么是Kubernetes?当今最流行的容器编排平台
  8. 8 Proxy是什么?正向代理、反向代理与SOCKS5详解
  9. 9 什么是Nginx?集Web服务器、反向代理与负载均衡于一体
✦ 快速摘要
什么是Kubernetes?深入了解当今最强大的容器编排平台:架构、Pod、Deployment、Service、自动扩缩容以及何时应该使用K8s。
这篇文章怎么样?

当系统中的容器数量从几个增长到数百、数千个时,手动管理变得无法实现。Kubernetes正是为解决这个问题而生——在整个服务器集群中自动调度、扩缩容和恢复容器,无需人工逐步干预。本文将解释什么是Kubernetes、其架构如何运作,以及何时真正需要使用它。

什么是Kubernetes?

Kubernetes(即K8s——因为K和s之间有8个字母而得名)是一个用于容器编排(container orchestration)的开源平台,即在多台服务器组成的集群上自动部署、扩缩容和管理容器的生命周期。它由Google基于内部的Borg系统开发,于2014年开源,并移交给云原生计算基金会(CNCF)管理。

可以将Kubernetes想象成容器乐团的指挥。每件乐器(容器)都了解自己的部分,但需要指挥来分配谁在何时演奏、替换生病的乐手,并确保整个乐团节奏协调。Kubernetes正是这样做的:将容器分配到哪个节点、在容器崩溃时重启它、在负载增加时增加副本数量。

Kubernetes解决的问题

当你只有一个小型应用时,Docker完全够用。但对于包含数十个服务的微服务架构,每个服务在多台服务器上运行多个副本,你会立即遇到以下问题:

  • 手动调度:哪个服务运行在哪台机器上?哪台机器还有资源?手动操作极其耗时。
  • 缺乏自我修复:凌晨3点容器崩溃了——谁来重启?Kubernetes会自动完成这件事。
  • 扩容复杂:流量突然增加,需要立即从2个副本扩展到10个——无法逐台SSH登录机器操作。
  • 滚动更新风险:在不停机的情况下部署新版本需要复杂的策略。
  • 服务发现:容器A需要调用容器B——每次重启后IP都在变化,如何知道地址?

Kubernetes通过一套声明式API(declarative API)解决了所有这些问题:你描述期望的状态,K8s负责将系统调整到该状态并持续维持它。

Docker和Kubernetes并非竞争关系

Docker将应用打包成容器镜像。Kubernetes在集群上编排这些容器。实际上,你使用Docker构建镜像、推送到镜像仓库,然后Kubernetes拉取镜像并运行它。两个工具相互补充。

Kubernetes架构

一个Kubernetes集群由两个主要层次组成:控制平面(Control Plane)工作节点(Worker Node)

控制平面

控制平面是集群的大脑,包含:

  • API Server:与集群所有交互的唯一入口。所有kubectl命令、webhook或CI/CD流水线都通过这里调用。
  • etcd:存储整个集群状态的分布式键值数据库。这是最重要的组件——失去etcd就失去了集群。
  • Scheduler:根据可用资源、亲和性规则和优先级决定新Pod将运行在哪个工作节点上。
  • Controller Manager:持续比较当前状态与期望状态并执行必要操作的控制循环集合(重启崩溃的Pod、扩容时创建新Pod等)。

工作节点

工作节点是实际运行容器的服务器,包含:

  • kubelet:运行在每个节点上的代理,接收来自API Server的指令并确保容器按规范运行。
  • kube-proxy:处理网络,根据Service规则将流量路由到正确的Pod。
  • 容器运行时:实际运行容器的组件(containerd、CRI-O——不一定是Docker)。

核心概念

Pod

Pod是Kubernetes中最小的部署单元。每个Pod包含一个或多个共享同一IP地址、网络命名空间和存储卷的容器。实际上,90%的Pod只有一个容器。Kubernetes不直接管理容器——它始终通过Pod进行操作。

Deployment

Deployment是声明Pod需要运行的副本数量以及如何更新它们的对象。当你部署新版本时,Deployment执行滚动更新——逐步用新Pod替换旧Pod,确保零停机。如果新版本出现故障,kubectl rollout undo可立即回滚。

Service

Service为一组Pod提供稳定的IP地址和DNS名称,即使Pod重启或更换IP,Service地址也不会改变。主要有三种类型:ClusterIP(集群内部)、NodePort(在节点上开放端口)、LoadBalancer(集成云的负载均衡器)。

Ingress

Ingress是从外部到集群的HTTP/HTTPS路由层,支持虚拟主机和基于路径的路由。例如:api.example.com/users → 服务A,api.example.com/orders → 服务B,全部通过单一入口点。

Namespace

Namespace是集群内部的逻辑分区机制,用于分隔环境(开发、预发布、生产)或在同一物理集群中分隔团队。

自动化:扩缩容、更新、自我修复

自动扩缩容

Kubernetes提供三个级别的自动扩缩容:

  • HPA(Horizontal Pod Autoscaler):根据CPU、内存或自定义指标增减Pod数量。
  • VPA(Vertical Pod Autoscaler):自动调整Pod的CPU/内存请求量。
  • Cluster Autoscaler:当集群需要更多或更少资源时自动添加/删除物理节点(与GKE、EKS、AKS集成)。

滚动更新与回滚

Bash
1# 更新Deployment的镜像
2kubectl set image deployment/my-app app=my-app:v2.1.0
3
4# 监控滚动更新进度
5kubectl rollout status deployment/my-app
6
7# 出现错误时回滚到上一版本
8kubectl rollout undo deployment/my-app

自我修复

Controller Manager持续检查:如果一个Pod崩溃,它会立即在有可用资源的节点上创建替代Pod。如果整个节点宕机,该节点上的所有Pod都会被重新调度到其他节点——自动完成,无需人工干预。

存活探针与就绪探针

Kubernetes使用**存活探针(liveness probe)来检测卡死(hung)的容器并重启它,使用就绪探针(readiness probe)**来判断容器是否已准备好接收流量。正确配置这两个探针是使自我修复有效运作的重要步骤。

工具:kubectl和Helm

kubectl

kubectl是与集群交互的主要CLI工具。以下是声明简单Deployment的YAML manifest示例:

YAML
 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: my-app
 5  namespace: production
 6spec:
 7  replicas: 3
 8  selector:
 9    matchLabels:
10      app: my-app
11  template:
12    metadata:
13      labels:
14        app: my-app
15    spec:
16      containers:
17        - name: app
18          image: my-app:v2.1.0
19          ports:
20            - containerPort: 8080
21          resources:
22            requests:
23              cpu: "100m"
24              memory: "128Mi"
25            limits:
26              cpu: "500m"
27              memory: "256Mi"
28          readinessProbe:
29            httpGet:
30              path: /healthz
31              port: 8080
32            initialDelaySeconds: 5
33            periodSeconds: 10

应用manifest:

Bash
1kubectl apply -f deployment.yaml
2kubectl get pods -n production
3kubectl describe pod <pod-name> -n production

Helm——Kubernetes的包管理器

Helm是Kubernetes的包管理工具(称为chart),类似于Node.js的npm。与其编写数十个独立的YAML文件,不如使用Helm将其打包成可参数化、可复用的chart。一个Helm chart包含带有变量的YAML模板,变量通过values.yaml文件填充,使得同一个chart只需替换values.yaml就能部署到开发、预发布和生产环境。

Bash
 1# 通过Helm安装nginx-ingress
 2helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
 3helm install ingress-nginx ingress-nginx/ingress-nginx \
 4  --namespace ingress-nginx \
 5  --create-namespace
 6
 7# 为生产环境覆盖默认值
 8helm upgrade --install my-app ./chart \
 9  -f values.production.yaml \
10  --namespace production

Helm还保存发布历史,允许使用helm rollback my-app 1回滚到上一版本——类似于kubectl rollout undo,但适用于包含多个资源的整个技术栈。将Helm与CI/CD流水线结合使用,是在生产环境中自动化部署到Kubernetes的最常见方式。

ConfigMap与Secret

这两个对象将配置与容器镜像分离。ConfigMap存储非敏感配置(数据库主机、功能标志);Secret以base64编码形式存储敏感数据(密码、API密钥)。两者都通过环境变量或卷挂载注入到Pod中,使同一镜像无需重新构建即可在多个不同环境中运行。

对比:托管K8s与自托管

Managed Kubernetes vs Self-Hosted
Tested on 2026-06-12 Kubernetes deployment options
| 标准 | 托管(GKE/EKS/AKS) | 自托管(kubeadm) | |---|---|---| | **控制平面安装** | 自动,几分钟 | 手动,数小时 | | **K8s升级** | 一键/自动 | 逐步手动操作 | | **etcd备份** | 内置集成 | 需自行配置 | | **费用** | 额外支付托管费 | 节省云服务费 | | **控制平面定制** | 受限 | 完全控制 | | **适用场景** | 大多数企业 | 需要深度定制 |

何时需要Kubernetes——以及何时是过度设计

适合使用Kubernetes的情况:

  • 系统有5个以上需要独立部署的微服务。
  • 需要根据实际负载进行自动扩缩容(例如:夜间流量突然增加)。
  • 要求零停机部署和快速回滚。
  • DevOps团队已具备集群运维经验。
  • 基础设施部署在支持托管K8s的云服务器上。

Kubernetes是过度设计的情况:

  • 处于早期阶段、只有1-3个服务的初创项目。
  • 团队规模小,没有专职的K8s运维人员。
  • 流量低且稳定,不需要自动扩缩容。
  • 预算有限——集群的开销(至少3个节点)比单台VPS更昂贵。

对于小型项目,Docker Compose或简单的CI/CD流水线部署到VPS就已足够。Kubernetes是强大的工具,但伴随着高度复杂性——只有在真正需要时才值得投入。

结论: Kubernetes解决了大规模容器编排问题,目前没有任何工具能做得更好。深入理解控制平面架构、Pod/Deployment/Service等核心概念,并了解何时应该使用它,将帮助你做出正确的决策——而不是仅仅因为它流行就将K8s应用于每个项目。

参考资料
  1. https://kubernetes.io/docs/concepts/overview/
  2. https://kubernetes.io/docs/concepts/architecture/
  3. https://kubernetes.io/docs/concepts/workloads/pods/
  4. https://helm.sh/docs/intro/quickstart/
  5. https://cloud.google.com/kubernetes-engine/docs/concepts/kubernetes-engine-overview
  6. https://martinfowler.com/articles/microservices.html

常见问题

常见问题Q&A
Kubernetes和Docker有什么区别?
Docker是在单台机器上打包和运行单个容器的工具。Kubernetes是其上层的编排层,可同时管理分布在多台服务器上的数百个容器。两种技术相辅相成:Docker负责创建容器,Kubernetes负责调度、扩缩容,并在容器发生故障时自动恢复。
Kubernetes中的Pod是什么?
Pod是Kubernetes中最小的部署单元,由一个或多个共享同一IP地址和存储的容器组成。通常每个Pod包含一个主容器;同一Pod中的辅助容器(sidecar)用于处理日志记录、代理或配置注入。当Pod发生故障时,Kubernetes会自动创建新的Pod来替代它。
小型项目需要Kubernetes吗?
大多数拥有不超过5个服务的小型项目不需要Kubernetes。运营集群的成本(配置、监控、安全)往往超过其带来的收益。Docker Compose或简单的VPS通常就已足够。当你拥有多个微服务、需要自动扩缩容或频繁进行零停机部署时,Kubernetes才能真正发挥其价值。
托管Kubernetes(GKE/EKS/AKS)和自托管有什么区别?
托管Kubernetes由云服务商运营控制平面,自动升级、修补安全漏洞并提供SLA正常运行时间保证。自托管提供完全的定制权限,但DevOps团队必须自行管理etcd备份、证书轮换和升级。对于大多数企业而言,托管方案是更实际的起点。
学习Kubernetes应该从哪里开始?
建议先扎实掌握Docker基础知识。然后在本地安装minikube或kind进行实践。按顺序学习:Pod → Deployment → Service → Ingress → ConfigMap/Secret。kubernetes.io/docs上的官方文档非常全面,并且直接在浏览器中提供了交互式教程。

When the number of containers in a system grows from a handful to hundreds or thousands, manual management becomes impossible. Kubernetes was built to solve exactly that problem — automatically scheduling, scaling, and recovering containers across an entire server cluster without requiring human intervention at every step. This article explains what Kubernetes is, how its architecture works, and when you truly need it.

What is Kubernetes?

Kubernetes (or K8s — abbreviated because there are 8 letters between K and s) is an open-source platform for container orchestration — automatically deploying, scaling, and managing the lifecycle of containers across a cluster of multiple servers. Google developed it internally from their Borg system, then open-sourced it in 2014 and handed it over to the Cloud Native Computing Foundation (CNCF) to manage.

Think of Kubernetes as the conductor of a container orchestra. Each instrument (container) knows its own part, but needs a conductor to assign who plays when, replace a musician who falls ill, and ensure the whole ensemble stays in time. Kubernetes does exactly that: assigns containers to nodes, restarts them when they crash, and scales up replicas when load increases.

Problems Kubernetes Solves

When you only have a small application, Docker is perfectly sufficient. But with a microservices architecture spanning dozens of services, each running multiple replicas across many servers, you quickly run into these problems:

  • Manual scheduling: Which service runs on which machine? Which machines still have resources? Doing this by hand is extremely time-consuming.
  • No self-healing: A container crashes at 3 AM — who restarts it? Kubernetes does this automatically.
  • Complex scaling: Traffic spikes and you need to scale from 2 to 10 replicas immediately — you can't SSH into each machine one by one.
  • Risky rolling updates: Deploying a new version without downtime requires a complex strategy.
  • Service discovery: Container A needs to call Container B — the IP changes constantly after every restart, so how do you know the address?

Kubernetes solves all of this with a declarative API: you describe the desired state, and K8s takes care of bringing the system to that state and maintaining it.

Docker and Kubernetes are not competing

Docker packages applications into container images. Kubernetes orchestrates those containers across a cluster. In practice, you use Docker to build images, push them to a registry, and then Kubernetes pulls the images and runs them. The two tools complement each other.

Kubernetes Architecture

A Kubernetes cluster consists of two main layers: the Control Plane and Worker Nodes.

Control Plane

The Control Plane is the brain of the cluster, consisting of:

  • API Server: The single entry point for all interactions with the cluster. Every kubectl command, webhook, or CI/CD pipeline call goes through here.
  • etcd: A distributed key-value database that stores the entire cluster state. This is the most critical component — lose etcd and you lose the cluster.
  • Scheduler: Decides which Worker Node a new Pod will run on, based on available resources, affinity rules, and priority.
  • Controller Manager: A set of control loops that continuously compare the current state with the desired state and take necessary actions (restarting crashed Pods, creating new Pods when scaling, etc.).

Worker Nodes

Worker Nodes are the actual servers that run containers, consisting of:

  • kubelet: An agent running on each node that receives instructions from the API Server and ensures containers run according to their spec.
  • kube-proxy: Handles networking and routes traffic to the correct Pod according to Service rules.
  • Container Runtime: The component that actually runs containers (containerd, CRI-O — not necessarily Docker).

Core Concepts

Pod

A Pod is the smallest deployable unit in Kubernetes. Each Pod contains one or more containers that share the same IP address, network namespace, and storage volumes. In practice, 90% of Pods contain just one container. Kubernetes does not manage containers directly — it always works through Pods.

Deployment

A Deployment is an object that declares the number of replicas of a Pod to run and how to update them. When you deploy a new version, the Deployment performs a rolling update — gradually replacing old Pods with new ones, ensuring no downtime. If the new version has issues, kubectl rollout undo reverts it immediately.

Service

A Service provides a stable IP address and DNS name for a group of Pods, so that even when Pods restart or change IPs, the Service address remains the same. There are three main types: ClusterIP (internal to the cluster), NodePort (opens a port on the node), and LoadBalancer (integrates with the cloud's load balancer).

Ingress

Ingress is an HTTP/HTTPS routing layer from outside the cluster into it, supporting virtual hosting and path-based routing. For example: api.example.com/users → Service A, api.example.com/orders → Service B, all through a single entry point.

Namespace

A Namespace is a mechanism for logical partitioning within a single cluster, used to separate environments (dev, staging, production) or separate teams within the same physical cluster.

Automation: Scaling, Updates, Self-Healing

Auto-Scaling

Kubernetes provides three levels of auto-scaling:

  • HPA (Horizontal Pod Autoscaler): Increases or decreases the number of Pods based on CPU, memory, or custom metrics.
  • VPA (Vertical Pod Autoscaler): Automatically adjusts the CPU/memory requests of a Pod.
  • Cluster Autoscaler: Automatically adds or removes physical Nodes when the cluster needs more or has excess resources (integrates with GKE, EKS, AKS).

Rolling Update and Rollback

Bash
1# Update the image of a Deployment
2kubectl set image deployment/my-app app=my-app:v2.1.0
3
4# Monitor the rolling update progress
5kubectl rollout status deployment/my-app
6
7# Rollback to the previous version if there is an issue
8kubectl rollout undo deployment/my-app

Self-Healing

The Controller Manager continuously checks: if a Pod crashes, it immediately creates a replacement Pod on a node with available resources. If an entire node goes down, all Pods on that node are rescheduled to other nodes — automatically, with no human intervention required.

Liveness and Readiness Probes

Kubernetes uses liveness probes to detect hung containers and restart them, and readiness probes to know when a container is ready to receive traffic. Configuring these two probes correctly is a critical step for self-healing to work effectively.

Tools: kubectl and Helm

kubectl

kubectl is the primary CLI for interacting with a cluster. Here is an example YAML manifest declaring a simple Deployment:

YAML
 1apiVersion: apps/v1
 2kind: Deployment
 3metadata:
 4  name: my-app
 5  namespace: production
 6spec:
 7  replicas: 3
 8  selector:
 9    matchLabels:
10      app: my-app
11  template:
12    metadata:
13      labels:
14        app: my-app
15    spec:
16      containers:
17        - name: app
18          image: my-app:v2.1.0
19          ports:
20            - containerPort: 8080
21          resources:
22            requests:
23              cpu: "100m"
24              memory: "128Mi"
25            limits:
26              cpu: "500m"
27              memory: "256Mi"
28          readinessProbe:
29            httpGet:
30              path: /healthz
31              port: 8080
32            initialDelaySeconds: 5
33            periodSeconds: 10

Apply the manifest:

Bash
1kubectl apply -f deployment.yaml
2kubectl get pods -n production
3kubectl describe pod <pod-name> -n production

Helm — Package Manager for Kubernetes

Helm is a package management tool (packages are called charts) for Kubernetes, similar to npm for Node.js. Instead of writing dozens of separate YAML files, Helm bundles them into a parameterized, reusable chart. A Helm chart consists of YAML templates with variables filled in through a values.yaml file, allowing the same chart to be deployed across dev, staging, and production environments simply by swapping values.yaml.

Bash
 1# Install nginx-ingress via Helm
 2helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx
 3helm install ingress-nginx ingress-nginx/ingress-nginx \
 4  --namespace ingress-nginx \
 5  --create-namespace
 6
 7# Override default values for the production environment
 8helm upgrade --install my-app ./chart \
 9  -f values.production.yaml \
10  --namespace production

Helm also stores release history, allowing helm rollback my-app 1 to revert to a previous version — similar to kubectl rollout undo but applied to an entire stack of multiple resources. Combining Helm with a CI/CD pipeline is the most common way to automate deployments to Kubernetes in production environments.

ConfigMap and Secret

These two objects separate configuration from the container image. ConfigMap stores non-sensitive configuration (database host, feature flags); Secret stores sensitive data (passwords, API keys) in base64-encoded form. Both are injected into Pods via environment variables or volume mounts, allowing the same image to run across multiple environments without needing to rebuild.

Comparison: Managed K8s vs Self-Hosted

Managed Kubernetes vs Self-Hosted
Tested on 2026-06-12 Kubernetes deployment options
| Criteria | Managed (GKE/EKS/AKS) | Self-Hosted (kubeadm) | |---|---|---| | **Control Plane Setup** | Automatic, minutes | Manual, hours | | **K8s Upgrades** | 1-click / automatic | Manual, step-by-step | | **etcd Backup** | Built-in | Configure yourself | | **Cost** | Extra managed fee | Saves cloud cost | | **Control Plane Customization** | Limited | Full control | | **Best For** | Most organizations | Deep customization needs |

When You NEED Kubernetes — and When It's Overkill

Use Kubernetes when:

  • Your system has 5+ microservices that need to be deployed independently.
  • You need auto-scaling based on real traffic (e.g., traffic spikes in the evening).
  • You require zero-downtime deployments and fast rollbacks.
  • Your DevOps team already has experience operating clusters.
  • Your infrastructure is on a cloud server that supports managed K8s.

Kubernetes is overkill when:

  • It's an early-stage startup project with 1-3 services.
  • The team is small with no one dedicated to operating K8s.
  • Traffic is low and stable, with no need for auto-scaling.
  • Budget is tight — the overhead of a cluster (at least 3 nodes) is more expensive than a single VPS.

For small projects, Docker Compose or a simple CI/CD pipeline deploying to a VPS is sufficient. Kubernetes is a powerful tool but comes with high complexity — only invest in it when it is truly necessary.

Conclusion: Kubernetes solves the container orchestration problem at scale better than any other tool available today. Understanding the Control Plane architecture, the concepts of Pod/Deployment/Service, and knowing when to use it will help you make the right decision — rather than applying K8s to every project simply because it is popular.

Sources
  1. https://kubernetes.io/docs/concepts/overview/
  2. https://kubernetes.io/docs/concepts/architecture/
  3. https://kubernetes.io/docs/concepts/workloads/pods/
  4. https://helm.sh/docs/intro/quickstart/
  5. https://cloud.google.com/kubernetes-engine/docs/concepts/kubernetes-engine-overview
  6. https://martinfowler.com/articles/microservices.html

Frequently Asked Questions

Frequently Asked QuestionsQ&A
How is Kubernetes different from Docker?
Docker is a tool for packaging and running individual containers on a single machine. Kubernetes is the orchestration layer on top, managing hundreds of containers distributed across many servers simultaneously. The two technologies complement each other: Docker creates containers, and Kubernetes handles scheduling, scaling, and self-healing when containers fail.
What is a Pod in Kubernetes?
A Pod is the smallest deployable unit in Kubernetes, consisting of one or more containers that share the same IP address and storage. Typically each Pod contains one main container; secondary containers (sidecars) within the same Pod are used for logging, proxying, or config injection. When a Pod fails, Kubernetes automatically creates a new Pod to replace it.
Do small projects need Kubernetes?
Most small projects with fewer than 5 services don't need Kubernetes. The operational overhead of running a cluster (configuration, monitoring, security) outweighs the benefits. Docker Compose or a simple VPS is usually sufficient. Kubernetes delivers real value when you have many microservices, need auto-scaling, or frequently require zero-downtime deployments.
How does managed Kubernetes (GKE/EKS/AKS) differ from self-hosted?
Managed Kubernetes has the cloud provider operating the Control Plane, handling automatic upgrades, security patches, and providing uptime SLAs. Self-hosted gives full customization control but the DevOps team must manage etcd backups, certificate rotation, and upgrades themselves. For most organizations, managed is the more practical starting point.
Where should I start when learning Kubernetes?
Start by getting a solid grasp of basic Docker first. Then install minikube or kind on your local machine to practice. Learn in sequence: Pod → Deployment → Service → Ingress → ConfigMap/Secret. The official documentation at kubernetes.io/docs is very comprehensive and includes interactive tutorials you can run directly in your browser.