第十二章 网络(下)

12.3.2  实践Network Policy

  当前没有配置任何Network Policy.

apiVersion: apps/v1beta1
kind: Deployment
metadata:
  name: httpd
spec:
  replicas: 3
  template:
    metadata:
      labels:
        run: httpd
    spec:
      containers:
      - name: httpd
        image: httpd:latest
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 80
        
---
apiVersion: v1
kind: Service
metadata:
  name: httpd-svc
spec:
  type: NodePort
  selector:
    run: httpd
  ports:
  - protocol: TCP
    nodePort: 30000
    port: 8080
    targetPort: 80
    

 如下,查看Pod和service:

kubeusr@GalaxyKubernetesMaster:~$ kubectl get pods -o wide
NAME                     READY     STATUS              RESTARTS   AGE       IP             NODE
httpd-65f9bdfb75-b5v49   0/1       ContainerCreating   0          3m        <none>         galaxykubernetes01
httpd-65f9bdfb75-nhpcb   1/1       Running             0          3m        10.244.3.89    galaxykubernetes04
httpd-65f9bdfb75-qdr2v   1/1       Running             0          3m        10.244.2.196   galaxykubernetes03


kubeusr@GalaxyKubernetesMaster:~$ kubectl get service httpd-svc
NAME        TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
httpd-svc   NodePort   10.102.11.34   <none>        8080:30000/TCP   6d

(1)启动一个busybox,在Pod里面既可以访问servcie也可以ping到Pod。

kubeusr@GalaxyKubernetesMaster:~$ kubectl exec -it busybox-577868d55b-h7df5 bin/sh       #进入Pod
/ # wget httpd-svc:8080
Connecting to httpd-svc:8080 (10.102.11.34:8080)
wget: can't open 'index.html': File exists
/ # rm -rf index.html
/ # wget httpd-svc:8080
Connecting to httpd-svc:8080 (10.102.11.34:8080)
index.html 100% |*****

 

/ # ping 10.244.3.89                                                      #  在Pod内部 Ping其他的Pod是可以通的
PING 10.244.3.89 (10.244.3.89): 56 data bytes
64 bytes from 10.244.3.89: seq=0 ttl=62 time=0.665 ms
64 bytes from 10.244.3.89: seq=1 ttl=62 time=0.538 ms

(2) 集群外可以访问service: 从我的windows电脑可以访问。

C:\Users\FeiLiu>curl 9.42.80.172:30000
<html><body><h1>It works!</h1></body></html>

 下面开始创建Network Policy:

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: access-httpd
spec:
  podSelector:
    matchLabels:
      run: httpd                          #  将访问规则应用于label为run: httpd的 pod,即httpd应用的的三个副本
  ingress:
  - from:
    - podSelector:
        matchLabels:
          access: "true"                  #  ingress中定义只有label为access:“true”的pod才能访问应用。(busybox已经不能访问了,需要加上access:"true"的Lable后才能访问)
    ports:
     - protocol: TCP
       port: 80                           #  只能访问80端口

 集群内节点和集群外的节点已经不能访问service。

  

posted @ 2019-01-05 15:53  刘大飞  阅读(450)  评论(0编辑  收藏  举报