创建Deployment与Service

  • Post author:
  • Post category:Kubernetes
  • Page Views 838 阅读

1.创建Deployment

fxx2@kube-node-1:~/yaml$ cat deploy-nginx.yaml
apiVersion: apps/v1 #指定api版本,此值必须在kubectl apiversion中,可用kubectl api-versions查看
kind: Deployment #资源类型
metadata: #资源的元数据/属性
name: nginx-deploy #资源的名字,在同一个namespace中必须唯一
spec: #资源规格说明
selector: #标签选择
matchLabels: #匹配标签
app: web_server #匹配标签为app:web_server的资源
revisionHistoryLimit: 4
replicas: 4 #指定pod副本数量,默认为1
template: #定义pod模板
metadata: #定义pod元数据
labels: #定义pod标签
app: web_server #pod标签
spec: #pod资源规格
containers: #容器
- name: nginx #定义容器名字
image: nginx:latest #指定容器镜像
imagePullPolicy: Never #三个选择Always、Never、IfNotPresent,每次启动时检查和更新(从registery)images的策略,
# Always,每次都检查
# Never,每次都不检查(不管本地是否有)
# IfNotPresent,如果本地有就不检查,如果没有就拉取
ports:
- containerPort: 80 #容器对外开放端口号

fxx2@kube-node-1:~/yaml$ sudo kubectl apply -f deploy-nginx.yaml
service/nginx-svc created
fxx2@kube-node-1:~/yaml$ sudo kubectl get pod -o wide
NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE READINESS GATES
nginx-deploy-749bb6d465-6bbph 1/1 Running 1 89m 10.244.0.208 kube-node-1 <none> <none>
nginx-deploy-749bb6d465-d46xg 1/1 Running 1 89m 10.244.0.204 kube-node-1 <none> <none>
nginx-deploy-749bb6d465-rnw4n 1/1 Running 1 89m 10.244.0.201 kube-node-1 <none> <none>
nginx-deploy-749bb6d465-t2wxj 1/1 Running 1 89m 10.244.0.211 kube-node-1 <none> <none>
fxx2@kube-node-1:~/yaml$

2.创建Service

fxx2@kube-node-1:~/yaml$ kubectl apply -f  svc-nginx.yaml
fxx2@kube-node-1:~/yaml$ cat svc-nginx.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx-svc
spec:
selector:
app: web_server #选择标签为app: web_server的pod为service的后端
ports:
- protocol: TCP
port: 8080 #将service的8080端口映射到pod的80端口
targetPort: 80

3.查看service与pod对应关系

查看Endpoints 字段

fxx2@kube-node-1:~/yaml$ sudo kubectl describe svc nginx-svc
Name: nginx-svc
Namespace: default
Labels: <none>
Annotations: kubectl.kubernetes.io/last-applied-configuration:
{"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"name":"nginx-svc","namespace":"default"},"spec":{"ports":[{"port":8080,"...
Selector: app=web_server
Type: ClusterIP
IP: 10.107.24.102
Port: <unset> 8080/TCP
TargetPort: 80/TCP
Endpoints: 10.244.0.201:80,10.244.0.204:80,10.244.0.208:80 + 1 more... #可知以和上面的pod已经关联
Session Affinity: None
Events: <none>

4.访问

通过service的ClusterIP进行访问

fxx2@kube-node-1:~/yaml$ curl -I 10.107.24.102:8080
HTTP/1.1 200 OK
Server: nginx/1.17.8
Date: Sat, 15 Feb 2020 15:28:27 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 21 Jan 2020 13:36:08 GMT
Connection: keep-alive
ETag: "5e26fe48-264"
Accept-Ranges: bytes


「 文章如果对你有帮助,请点个赞哦^^ 」 

0