这样对于访问这个服务带来了难度。因此,kubernetes设计了Service来解决这个问题。
Service可以看作是一组同类Pod对外的访问接口。借助Service,应用可以方便地实现服务发现和负载均衡。
#创建
[root@master ~]# kubectl create ns yhm
namespace/yhm created
[root@master ~]# kubectl create deploy nginx --image=nginx:latest --port=80 --replicas=3 -n yhm
deployment.apps/nginx created
#暴露Service
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx1 --type=ClusterIP --port=80 --target-port=80 -n yhm
service/svc-nginx1 exposed
# 查看service
[root@master ~]# kubectl get svc svc-nginx1 -n yhm -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
svc-nginx1 ClusterIP 10.109.147.6 <none> 80/TCP 26s app=nginx
# 这里产生了一个CLUSTER-IP,这就是service的IP,在Service的生命周期中,这个地址是不会变动的
# 可以通过这个IP访问当前service对应的POD
[root@master ~]# kubectl get svc svc-nginx1 -n yhm -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
svc-nginx1 ClusterIP 10.109.147.6 <none> 80/TCP 89s app=nginx
[root@master ~]# curl 10.109.147.6
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html {
color-scheme: light dark; }
body {
width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
# 上面创建的Service的type类型为ClusterIP,这个ip地址只用集群内部可访问# 如果需要创建外部也可以访问的Service,需要修改type为NodePort
[root@master ~]# kubectl expose deploy nginx --name=svc-nginx2 --type=NodePort --port=80 --target-port=80 -n yhm
service/svc-nginx2 exposed
# 此时查看,会发现出现了NodePort类型的Service,而且有一对Port(80:32349/TCP )
[root@master ~]# kubectl get svc svc-nginx2 -n yhm -o wide
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR
svc-nginx2 NodePort 10.109.247.254 <none> 80:31403/TCP 38s app=nginx
# 接下来就可以通过集群外的主机访问 节点IP:31403访问服务了# 例如在的电脑主机上通过浏览器访问下面的地址http://192.168.223.176:31403/
删除Service
[root@master ~]# kubectl delete svc svc-nginx2 -n yhm
service "svc-nginx2" deleted
配置方式
创建一个svc-nginx.yaml,内容如下:
[root@master ~]# vim svc-nginx.yaml
[root@master ~]# cat svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:
name: svc-nginx
namespace: yhm
spec:
clusterIP: 10.109.247.254
ports:
- port: 80
protocol: TCP
targetPort: 80
selector:
run: nginx
type: ClusterIP
[root@master ~]# kubectl create -f svc-nginx.yaml
service/svc-nginx created
[root@master ~]# kubectl delete -f svc-nginx.yaml
service "svc-nginx" deleted
apiVersion: v1 #必选,版本号,例如v1
kind: Pod #必选,资源类型,例如 Pod
met