1. Pod 中的端口配置
Pod 是 Kubernetes 中最小的调度单元,端口配置在 Pod 中用于定义容器暴露的端口。
关键字段:
|
|
apiVersion: v1 kind: Pod metadata: name: my-pod spec: containers: - name: my-container image: nginx ports: - name: http containerPort: 80 # 容器内应用监听的端口 protocol: TCP |
作用:
Deployment 中的端口配置
Deployment 是管理 Pod 副本的更高层抽象,其端口配置实际是通过 Pod 模板(spec.template.spec)定义的,与 Pod 的配置完全一致。
|
|
apiVersion: apps/v1 kind: Deployment metadata: name: my-deployment spec: replicas: 3 template: spec: containers: - name: nginx image: nginx ports: - containerPort: 80 # 与 Pod 中的定义相同 |
作用:
Service 中的端口配置
Service 用于将一组 Pod 暴露为网络服务,其端口配置定义了服务的访问规则。
关键字段:
|
|
apiVersion: v1 kind: Service metadata: name: my-service spec: type: ClusterIP ports: - name: http port: 80 # Service 的端口 targetPort: 80 # 指向 Pod 的 containerPort selector: app: nginx |
作用:
常见场景示例
场景:Service 端口与 Pod 端口不同
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
# Pod/Deployment 定义容器端口 8080 apiVersion: apps/v1 kind: Deployment spec: template: spec: containers: - ports: - containerPort: 8080 # 容器内端口 # Service 将端口 80 映射到 Pod 的 8080 apiVersion: v1 kind: Service spec: ports: - port: 80 # 外部访问 Service 的端口 targetPort: 8080 # 指向 Pod 的端口 |
场景:多端口 Service
|
|
apiVersion: v1 kind: Service spec: ports: - name: http port: 80 targetPort: 80 - name: metrics port: 9090 targetPort: 9090 |
总结
-
Pod 的 containerPort 是声明性的,仅说明容器监听的端口。
-
Deployment 通过 Pod 模板继承 Pod 的端口配置。
-
Service 的 targetPort 必须与 Pod 的 containerPort 匹配,而 port 是 Service 自身的虚拟端口。
在 Kubernetes 的 YAML 配置文件中,metadata.name、metadata.labels.app、spec.selector 这些字段在 Pod、Deployment 和 Service 中均有出现,但它们的用途和关联逻辑不同。以下是它们的区别和联系:
metadata.name
作用
|
|
apiVersion: v1 kind: Pod metadata: name: my-pod # Pod 的名称,在命名空间中必须唯一 |
metadata.labels 和 metadata.labels.app
作用
-
标签(Labels):metadata.labels 是键值对(如 app: nginx),用于标记资源(如 Pod、Deployment、Service),方便其他资源(如 Service、Deployment)通过 selector 筛选匹配的资源。
-
常见约定:metadata.labels.app 是一个常用标签,通常表示应用名称(如 app: nginx),但 Kubernetes 本身不强制要求使用 app,可以自定义(如 tier: frontend)。
|
|
apiVersion: v1 kind: Pod metadata: name: my-pod labels: app: nginx # 标记 Pod 属于 "nginx" 应用 tier: frontend # 自定义标签,表示前端服务 |
spec.selector
作用
|
|
apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment spec: selector: matchLabels: app: nginx # 选择所有 labels.app=nginx 的 Pod template: # 创建的 Pod 会自动带上 labels.app=nginx metadata: labels: app: nginx spec: containers: - name: nginx image: nginx |
|
|
apiVersion: v1 kind: Service metadata: name: nginx-service spec: selector: app: nginx # 代理所有 labels.app=nginx 的 Pod ports: - port: 80 targetPort: 80 |
三者的联系
-
metadata.labels 是标记,用于标识资源(如 Pod)。
-
spec.selector 是选择器,用于匹配带有特定 labels 的资源(如 Deployment 选择 Pod,否则无法管理 Pod。Service 选择 Pod,否则无法代理流量)。
-
metadata.name 是唯一标识,不直接影响绑定,但可用于手动查找资源。
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 - pod、deployment、service端口、标签区别与联系