K8s service
Service 定义
k8s Service
A Service is an object (the same way that a Pod or a ConfigMap is an object). You can create, view or modify Service definitions using the Kubernetes API. Usually you use a tool such as kubectl to make those API calls for you.
操作命令
配置文件
apiVersion: v1
kind: Service #资源类型:Service
metadata:
name: nginx-svc #Service 名字
labels:
app: nginx #Service自己本身的标签
spec:
ports: #端口映射
- port: 80 #Service自己的端口,在使用内网ip访问时候使用
targetPort: 80 #目标po的端口
name: web #为端口起的名字
selector: #匹配哪些pod会被该Service代理
app: nginx-deploy #所有匹配到该标签的pod都可以通过该Service进行网络访问
type: NodePort #1.随机启动一个端口(3000~32767),映射到ports中的端口,直接绑定到node上,切集群中的每个node都会绑定到这个端口。
#2.也可以用于将服务暴露给外部访问,但这种方式实际生产环境不推荐,效率低,而且Service是四层负载,而是用ingress
#(这个type类型有:NodePort、ClusterIP、ExternalName、LoadBalancer)
创建 service
查看 service 信息,通过 service 的 cluster ip 进行访问 查看 pod 信息,通过 pod 的 ip 进行访问 创建其他 pod 通过 service name 进行访问(推荐)exec官方解释kubectl exec -it busybox -- sh
curl http://nginx-svc
#创建的命令: kubectl run -it --image busbox dns-test -- /bin/sh
Endpoint
apiVersion: v1
kind: Endpoints
metadata:
labels:
app: nginx # 与 service 一致
name: nginx-svc-external # 与 service 一致
namespace: default # 与 service 一致
subsets:
- addresses:
- ip: 120.78.159.117 # 目标 ip 地址
ports: # 与 service 一致
- name: web #与service一致
port: 80
protocol: TCP
```
## 代理k8s外部服务
```yaml
apiVersion: v1
kind: Service
metadata:
labels:
app: wolfcode-external-domain
name: wolfcode-external-domain
spec:
type: ExternalName
externalName: www.wolfcode.cn
反向代理外部域名
apiVersion: v1
kind: Service
metadata:
labels:
app: wolfcode-external-domain
name: wolfcode-external-domain
spec:
type: ExternalName
externalName: www.wolfcode.cn
常用类型
- ClusterIP
只能在集群内部使用,不配置类型的话默认就是 ClusterIP
- ExternalName
返回定义的 CNAME 别名,可以配置为域名
- NodePort
会在所有安装了 kube-proxy 的节点都绑定一个端口,此端口可以代理至对应的 Pod,集群外部可以使用任意节点 ip + NodePort 的端口号访问到集群中对应 Pod 中的服务。
当类型设置为 NodePort 后,可以在 ports 配置中增加 nodePort 配置指定端口,需要在下方的端口范围内,如果不指定会随机指定端口
端口范围:30000~32767
端口范围配置在 /usr/lib/systemd/system/kube-apiserver.service 文件中
- LoadBalancer
使用云服务商(阿里云、腾讯云等)提供的负载均衡器服务