通过资源定义的方式创建haproxy的pod进行负载均衡
1. 运行两个httpd
[root@master haproxy]# vim Dockerfile
[root@master haproxy]# cat Dockerfile
FROM busybox
RUN mkdir /data && \
echo "the is test1" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master haproxy]# docker build -t dockerimages123/httpd:v0.1 .
[root@master web]# vim Dockerfile
[root@master web]# cat Dockerfile
FROM busybox
RUN mkdir /data && \
echo "the is test2" > /data/index.html
ENTRYPOINT ["/bin/httpd","-f","-h","/data"]
[root@master web]# docker build -t dockerimages123/httpd:v2.0 .
// 将这两个镜像运行为pod
[root@master haproxy]# cat web01.yml
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: web01
name: web01
spec:
replicas: 1
selector:
matchLabels:
app: web01
template:
metadata:
labels:
app: web01
spec:
containers:
- image: dockerimages123/httpd:v0.1
imagePullPolicy: IfNotPresent
name: web01
---
apiVersion: v1
kind: Service
metadata:
name: web01
spec:
ports:
- port: 80
targetPort: 80
selector:
app: web01
[root@master haproxy]# cat web02.yml
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: web02
name: web02
spec:
replicas: 1
selector:
matchLabels:
app: web02
template:
metadata:
labels:
app: web02
spec:
containers:
- name: web02
image: dockerimages123/httpd:v2.0
imagePullPolicy: IfNotPresent
---
apiVersion: v1
kind: Service
metadata:
name: web02
spec:
ports:
- port: 80
targetPort: 80
selector:
app: web02
[root@master haproxy]# kubectl create -f web01.yml
deployment.apps/web01 created
service/web01 created
[root@master haproxy]# kubectl create -f web02.yml
deployment.apps/web02 created
service/web02 created
2. 编写资源清单定义haproxy
[root@master haproxy]# cat haproxy.yml
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: haproxy
name: haproxy
namespace: default
spec:
replicas: 1
selector:
matchLabels:
app: haproxy
template:
metadata:
labels:
app: haproxy
spec:
containers:
- name: haproxy
image: dockerimages123/haproxy-apline:latest
env:
- name: RSIP
value: 'web01 web02'
---
apiVersion: v1
kind: Service
metadata:
name: haproxy
spec:
ports:
- port: 80
targetPort: 80
selector:
app: haproxy
type: NodePort
测试
[root@master haproxy]# kubectl get pod,svc
[root@master haproxy]# kubectl get pod,svc
NAME READY STATUS RESTARTS AGE
pod/haproxy-7f745cff47-77kxh 1/1 Running 0 94s
pod/web01-6cd64b79f6-fffxv 1/1 Running 0 4m5s
pod/web02-55f6787ccf-swwks 1/1 Running 0 3m35s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
haproxy NodePort 10.103.16.159 <none> 80:30227/TCP 6s
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5d6h
nginx ClusterIP 10.105.50.111 <none> 8080/TCP 2d2h
web01 ClusterIP 10.108.27.105 <none> 80/TCP 149m
web02 ClusterIP 10.109.190.25 <none> 80/TCP 149m
[root@master haproxy]# curl 192.168.182.150:30227
the is test1
[root@master haproxy]# curl 192.168.182.150:30227
the is test2