编写Service.yml文件
[root@master ~]# cat nginx.yml
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
volumes:
- name: webstorage
hostPath:
path: /var/www/html
containers:
- name: web
image: nginx
imagePullPolicy: IfNotPresent
volumeMounts:
- name: webstorage
mountPath: /usr/share/nginx/html
...
---
apiVersion: v1
kind: Service
metadata:
name: web
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
protocol: TCP
nodePort: 30000
selector:
app: nginx
执行
[root@master ~]# kubectl apply -f nginx.yml
deployment.apps/web created
service/web created
查看
[root@master ~]# kubectl get pod
NAME READY STATUS RESTARTS AGE
web-6cfcd88d4-4rh75 1/1 Running 0 5s
web-6cfcd88d4-ql4k6 1/1 Running 0 5s
[root@master ~]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 3d1h
web NodePort 10.110.225.36 <none> 80:30000/TCP 68s
访问测试:
//这里用node1或node2的IP+30000端口号访问
[root@node1 ~]# curl http://192.168.160.124:30000
test11111111111111111111111111111111111111111111111
[root@node2 ~]# curl http://192.168.160.125:30000
test222222222222222222222222222222222222222222222222
浏览器访问
另外开一台主机安装nginx做负载均衡用
[root@localhost ~]# yum -y install nginx
修改nginx配置文件
//在server前添加
upstream webcluster {
server 192.168.160.124:30000;
server 192.168.160.125:30000;
}
//在server里面添加
location / {
proxy_pass http://webcluster:30000;
}
重启Nginx
[root@localhost ~]# systemctl restart nginx.service
[root@localhost ~]# ss -anlt
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128 0.0.0.0:80 0.0.0.0:*
LISTEN 0 128 0.0.0.0:22 0.0.0.0:*
LISTEN 0 128 [::]:80 [::]:*
LISTEN 0 128 [::]:22 [::]:*
查看IP地址
[root@localhost ~]# ifconfig
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.160.120 netmask 255.255.255.0 broadcast 192.168.160.255
inet6 fe80::625d:a3c1:31a8:b7ca prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:14:34:68 txqueuelen 1000 (Ethernet)
RX packets 3635 bytes 310215 (302.9 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2960 bytes 429431 (419.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 12 bytes 1020 (1020.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 12 bytes 1020 (1020.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
访问测试:
[root@localhost ~]# curl http://127.0.0.1
test11111111111111111111111111111111111111111111111
[root@localhost ~]# curl http://127.0.0.1
test222222222222222222222222222222222222222222222222
评论区