
Kubernetes Service是集群中定义Pod访问策略的核心资源对象,它为Pod提供稳定的网络访问入口,使应用可以稳定地被访问而不受后端Pod变化的影响。本文将详细解析Service的关键字段配置,帮助您全面掌握Service的配置技巧。
apiVersion: v1
kind: Service
metadata:
name: web-service
namespace: production
labels:
app: web-app
environment: prodspec:
selector:
app: web-app
tier: frontend
ports:
- name: http
protocol: TCP
port: 80
targetPort: 8080spec:
type: ClusterIP # 可省略,默认值
clusterIP: 10.0.0.10 # 可选,指定ClusterIPspec:
type: NodePort
ports:
- port: 80
targetPort: 8080
nodePort: 31080 # 可选,范围30000-32767spec:
type: LoadBalancer
externalTrafficPolicy: Local
loadBalancerIP: 203.0.113.10 # 可选,指定负载均衡器IPspec:
type: ExternalName
externalName: my.database.example.comspec:
ports:
- name: http
protocol: TCP
port: 80
targetPort: 8080
- name: https
protocol: TCP
port: 443
targetPort: 8443
- name: metrics
protocol: TCP
port: 9090
targetPort: metrics-port # 可引用Pod中定义的端口名称spec:
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP:
timeoutSeconds: 3600 # 默认10800秒(3小时)spec:
externalIPs:
- 192.168.1.100
- 10.0.0.100spec:
publishNotReadyAddresses: false # 默认值apiVersion: v1
kind: Service
metadata:
name: ecommerce-service
namespace: production
labels:
app: ecommerce
tier: frontend
annotations:
service.beta.kubernetes.io/aws-load-balancer-type: "nlb"
spec:
type: LoadBalancer
selector:
app: ecommerce
tier: frontend
ports:
- name: http
protocol: TCP
port: 80
targetPort: 8080
- name: https
protocol: TCP
port: 443
targetPort: 8443
sessionAffinity: ClientIP
sessionAffinityConfig:
clientIP:
timeoutSeconds: 7200
externalTrafficPolicy: Local
loadBalancerSourceRanges:
- 203.0.113.0/24
- 198.51.100.0/24
healthCheckNodePort: 32080 # 指定健康检查端口通过合理配置Service字段可以构建稳定、安全且高效的服务访问机制,为Kubernetes集群中的应用程序提供可靠的网络连接。
1、命名规范:使用 <应用名>-service 格式命名,如 user-service
2、端口配置:为每个端口指定名称,便于维护
3、标签选择器:使用多个标签精确匹配Pod,如 app: frontend, environment: prod
4、安全配置:
5、性能优化:
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!