当前位置: 首页> 娱乐> 明星 > Kubernetes Service 之 LoadBalancer

Kubernetes Service 之 LoadBalancer

时间:2025/7/29 23:23:38来源:https://blog.csdn.net/baidu_34688878/article/details/140559748 浏览次数:0次

Kubernetes 之 LoadBalancer

定义

负载均衡器 (LoadBalancer) 是 Kubernetes 中用来对外暴露 Service 服务的,它可以将服务集中到一个公共 IP 上。我们常用 MetalLB 作为自建均衡器。

使用

安装 MetalLB

kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.14.7/config/manifests/metallb-native.yaml

配置 ARP IP 池

apiVersion: metallb.io/v1beta1
kind: IPAddressPool
metadata:name: first-poolnamespace: metallb-system
spec:addresses:- 192.168.31.70-192.168.31.90
kubectl apply -f metalb-ips.yml

导入新镜像statis-web-1.0.90.tar

ctr -n=k8s.io images import static-web-1.0.90.tar
// go 语言编写的 web static 镜像代码
package mainimport ("fmt""net/http""os"
)func main() {htmlContent := os.Getenv("HTML_BODY_CONTENT")if htmlContent == "" {htmlContent = "<html><body><h1>No Content Set</h1></body></html>"} else {htmlContent = "<html><body><h1>" + htmlContent + "</h1></body></html>"}http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {_, _ = fmt.Fprint(w, htmlContent)})port := ":80"fmt.Printf("Server is listening on port %s\n", port)err := http.ListenAndServe(port, nil)if err != nil {fmt.Printf("Error starting server: %v\n", err)}
}

创建测试 Deployment 和 Service

apiVersion: apps/v1
kind: Deployment
metadata:name: deployment-web-staticnamespace: defaultlabels:app: deployment-web-static
spec:replicas: 2selector:matchLabels:app: pod-web-statictemplate:metadata:labels:app: pod-web-staticspec:containers:- name: web-staticimage: static-web:1.0.90imagePullPolicy: IfNotPresentports:- containerPort: 80env:- name: HTML_BODY_CONTENTvalue: "This is a test"
---
apiVersion: v1
kind: Service
metadata:name: service-static-webnamespace: defaultlabels:app: service-static-web
spec:type: LoadBalancerports:- port: 80protocol: TCPtargetPort: 80selector:app: pod-web-static

测试

root@k8s-master1:~# kubectl get service
NAME                 TYPE           CLUSTER-IP      EXTERNAL-IP     PORT(S)        AGE
kubernetes           ClusterIP      10.96.0.1       <none>          443/TCP        67d
service-static-web   LoadBalancer   10.102.54.255   192.168.31.70   80:30487/TCP   3m13s
root@k8s-master1:~# curl 192.168.31.70
<html><body><h1>This is a test</h1></body></html>
关键字:Kubernetes Service 之 LoadBalancer

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: