k8s入门之Service(六) - 景少
source link: https://www.cnblogs.com/chuandao/p/16176636.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
k8s入门之Service(六)
将一组pod公开为网络服务,通过service代理,可以实现负载均衡
一、ClusterIP
此方式只能在集群内访问
1.使用命令暴露已存在的pod
(1)继续使用前面章节的案例,查看名称为nginx的deploy下的pod
kubectl get pod -n dev -owide
进入每个pod容器,更改index.html内容
kubectl exec nginx-6799fc88d8-2rf2c -it /bin/bash -n dev
cd /usr/share/nginx/html/
rm -rf index.html
touche index.html
echo 1111 >> index.html
kubectl exec nginx-6799fc88d8-rnhmd -it /bin/bash -n dev
cd /usr/share/nginx/html/
rm -rf index.html
touche index.html
echo 2222 >> index.htm
(2)使用curl命令访问pod的ip,查看更改后的结果
(3)通过ClusterIP的方式暴露pod,默认就是ClusterIP
kubectl expose deploy nginx --name=svc-nginx --port=8000 --target-port=80 --type=ClusterIP -n dev
(4)查看暴露后的service
kubectl get svc -n dev
可以看到分配了一个ClusterIP
(5)访问ClusterIp,查看结果
service把请求负载均衡的分发给后面代理的pod进行处理,可以看到输出结果不一样
(6) 在容器内部通过域名的方式访问:服务名.命名空间.svc:port
进入某个pod容器
kubectl exec nginx-6799fc88d8-2rf2c -n dev -it /bin/bash
在容器内部执行curl命令访问服务的域名
2.删除服务
kubectl delete svc svc-nginx -n dev
3.通过yaml创建服务
编写svc-nginx.yaml文件
apiVersion: v1
kind: Service
metadata:
labels:
app: svc-nginx
name: svc-nginx
namespace: dev
spec:
selector:
#选择指定标签的Deployment
app: nginx
type: ClusterIP
ports:
- port: 8000
protocol: TCP
targetPort: 80
创建nginx服务
kubectl apply -f svc-nginx.yaml
二、NodePort
此方式不仅能在集群内访问,也可以在集群外部访问,NodePort范围在 30000-32767 之间
1.使用命令暴露已存在的pod
(1)继续使用前面章节的案例,查看名称为nginx的deploy下的pod
kubectl get pod -n dev -owide
进入每个pod容器,更改index.html内容
kubectl exec nginx-6799fc88d8-2rf2c -it /bin/bash -n dev
cd /usr/share/nginx/html/
rm -rf index.html
touche index.html
echo 1111 >> index.html
kubectl exec nginx-6799fc88d8-rnhmd -it /bin/bash -n dev
cd /usr/share/nginx/html/
rm -rf index.html
touche index.html
echo 2222 >> index.htm
(2)使用curl访问pod的ip查看更改后的结果
(3)通过NodePort的方式暴露pod,不指定--name参数,service的名称默认为deploy的名称
kubectl expose deploy nginx --port=8000 --target-port=80 --type=NodePort -n dev
(4)查看暴露后的service
kubectl get svc -n dev
(5)在集群内访问ClusterIp,查看结果
service把请求负载均衡的分发给后面代理的pod进行处理
(6)在集群外访问
2.删除服务
kubectl delete svc nginx -n dev
3.通过yaml创建服务
apiVersion: v1
kind: Service
metadata:
labels:
app: svc-nginx
name: svc-nginx
namespace: dev
spec:
selector:
#选择指定标签的Deployment
app: nginx
#注意指定type为NodePort
type: NodePort
ports:
- port: 8000
protocol: TCP
targetPort: 80
#指定暴露的端口号,不设置就默认随机一个
#nodePort: 31234
创建成功之后,可以使用上面介绍的方法来查看测试服务
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK