跳到主要内容

Deployment Service

2024年11月13日
柏拉文
越努力,越幸运

一、认识


Kubernetes 中的 Deployment 是一种高层级的控制器,负责管理和维护应用的 PodReplicaSet。它为用户提供了声明式更新、版本回滚和副本管理等功能。它简化了应用的滚动更新、扩缩容、回滚等操作。通过 Deployment,我们可以方便地部署和管理无状态应用,确保应用的多个副本持续运行并保持高可用性。Deployment Service 通常使用标准的 ClusterIPLoadBalancer 服务,通过单一入口访问所有 Pod。适用于快速扩缩容的无状态应用,通过负载均衡统一分发流量,通常结合标准 Service 使用。

1.1 绑定规则

DeploymentService 的绑定规则为: ServiceselectorDeployment 中的 Pod 标签匹配,用于绑定 Pod

service.yaml: selector 用于匹配 deployment.yaml 中的 spec.selector.matchLabels

apiVersion: v1
kind: Service
metadata:
name: test-service
spec:
selector:
app: test-nginx

deployment.yaml: spec.selector.matchLabels 用于匹配 service.yaml 中的 selector。但是 deployment.yaml 中的 spec.selector.matchLabels 必须与 spec.template.metadata.labels 一致。

apiVersion: apps/v1
kind: Deployment
spec:
selector:
matchLabels:
app: test-nginx
template:
metadata:
labels:
app: test-nginx

1.2 Deployment

Deployment Pod 没有固定标识,随时可以删除、重建。没有持久存储,每次重建会清空数据。Pod 名称动态分配,每次重建可能会改变。容易快速增加或减少 Pod 数量。自动更新 Pod,确保服务不中断。无法直接访问某个 Pod,所有 Pod 共享一个服务入口, 通过标准 Service 对所有 Pod 实现负载均衡随机分配流量。

二、操作


2.1 编写 Service 文件

我们构建一个 Service,使得它可以被访问。这里我们选择 NodePort 类型的 Service,以便在集群外部通过节点 IP 和端口访问。创建一个简单的 test-service.yaml 文件

apiVersion: v1
kind: Service
metadata:
name: test-service
spec:
selector:
app: test-nginx
type: NodePort
ports:
- protocol: TCP
port: 80
targetPort: 80
nodePort: 30000

2.2 创建 Service 服务

应用这个 Service

kubectl apply -f test-service.yaml

2.3 编写 Deployment 文件

我们创建一个简单的 test-deployment.yaml 文件,并确保它运行多个副本以便测试负载均衡

apiVersion: apps/v1
kind: Deployment
metadata:
name: test-deployment
spec:
replicas: 3
selector:
matchLabels:
app: test-nginx
template:
metadata:
labels:
app: test-nginx
spec:
containers:
- name: test-nginx
image: registry.cn-hangzhou.aliyuncs.com/bolawen/nginx:1.27.1-perl-linux-arm64
ports:
- containerPort: 80

2.4 创建 Deployment 应用

应用这个 Deployment

kubectl apply -f test-deployment.yaml

2.5 查看 Service 状态

查看整体状态

kubectl get all 

查看 Pod 状态

kubectl get pods 

检查 Service 状态

kubectl get service test-service

查看 service 详细信息

kubectl describe service test-service

查看 EndPoints 详细信息

kubectl get endpoints test-service

2.6 访问 Service 服务

使用以下命令查看 Service 的信息

kubectl get service test-service

在输出中,查看 NodePort 列中的端口(例如 30000),然后可以通过以下方式访问 Nginx: 其中 <NodeIP> 是集群中任意节点的 IP 地址。

http://<NodeIP>:30000

可以在浏览器或命令行(如 curl)中多次访问 Service URL,查看它是否将流量负载均衡到不同的 Pod 实例上。

2.7 删除 Service 服务

kubectl delete -f test-service.yaml

2.8 访问 Service Pod 容器

kubectl get pods // 获得 Pod Name 

kubectl exec -it [Pod Name] -- sh/bash

printenv // 进入容器后,查看环境变量

三、场景


3.1 在集群内部访问应用

在集群内部访问应用: 使用 ClusterIP 类型服务,例如将微服务 A 通过 Service 暴露给微服务 B,保证微服务之间的稳定通信。

3.2 在集群外部访问服务

在集群外部访问服务: 使用 NodePortLoadBalancer 类型的 Service,将服务公开以供外部客户端访问。

3.3 跨集群服务调用

跨集群服务调用: 使用 ExternalName 将内部服务映射到外部服务,简化跨集群或跨网络的服务调用。