用nginx对k8s集群中的service做负载均衡
| 主机IP | 角色 |
|---|
| 192.168.218.133 | master |
| 192.168.218.130 | node1 |
| 192.168.218.144 | node2 |
| 192.168.218.132 | nginx |
[root@master manifest]# cat test.yml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: default
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
imagePullPolicy: IfNotPresent
volumeMounts:
- mountPath: /usr/share/nginx/html
name: nginx-index
volumes:
- name: nginx-index
hostPath:
path: /var/www/html
---
apiVersion: v1
kind: Service
metadata:
name: web
namespace: default
spec:
ports:
- port: 80
protocol: TCP
targetPort: 80
nodePort: 30000
selector:
app: nginx
type: NodePort
//运行pod
[root@master manifest]# kubectl get pods -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
web-579695c7d4-l2j7s 1/1 Running 0 5m17s 10.244.2.58 node2.example.com
web-579695c7d4-p7mzl 1/1 Running 0 4m19s 10.244.1.25 node1.example.com
[root@master manifest]# curl 192.168.218.130:30000
hello world
[root@master manifest]# curl 192.168.218.144:30000
hello k8s
[root@nginx ~]# yum -y install nginx
[root@nginx ~]# vi /etc/nginx/nginx.conf
......
upstream webservers {
server 192.168.218.130:30000;
server 192.168.218.144:30000;
}
server{
listen 8080;
location / {
proxy_pass http://webservers;
}
}
......
[root@nginx ~]# systemctl start nginx
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:8080 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:80 [::]:*
LISTEN 0 128 [::]:22 [::]:*
[root@nginx ~]# curl 192.168.218.132:8080
hello k8s
[root@nginx ~]# curl 192.168.218.132:8080
hello k8s
[root@nginx ~]# curl 192.168.218.132:8080
hello world
[root@nginx ~]# curl 192.168.218.132:8080
hello k8s
[root@nginx ~]# curl 192.168.218.132:8080
hello k8s
[root@nginx ~]# curl 192.168.218.132:8080
hello k8s
[root@nginx ~]# curl 192.168.218.132:8080
hello world