如何使用 Kubernetes 里的 NetworkPolicy

创建一个类型为 NetworkPolicy 的 Kubernetes 对象的 yaml 文件。
第九行的 podSelector 指定这个 NetworkPolicy 施加在哪些 pod 上,通过 label 来做 pod 的过滤。

从第 16 行开始的 ingress 定义,定义了只有具备标签 component=ads,module=app 的 pod 才能够连接 component=ads, module=db 的 pod。
首先创建一个临时的 pod,使用正确的 label(component=ads,module=app)去访问 db pod:
kubectl run --restart=Never -it --rm --image=postgres:9.6 --labels="component=ads,module=app" --env="PGCONNECT_TIMEOUT=5" helper --command -- /bin/bash
执行完毕后看到提示 root@helper:/#, 说明我通过上述命令创建的临时 pod 成功的连接到了 postgreSQL 的 pod 上。

输入正确的用户名和密码,能成功连接到 postgreSQL pod 提供的数据库服务上。

现在我们重新创建一个临时 pod,不指定 label,因此不满足 NetworkPolicy 里定义的限制条件,因此会看到我们期望的结果:postgreSQL 连接失败。

希望通过例子大家能够理解 Kubernetes 里 NetworkPolicy 的工作原理。
通过一个例子学习 Kubernetes 里的 PersistentVolumeClaim 的用法
Kubernetes 的 pod 本身是无状态的(stateless),生命周期通常比较短,只要出现了异常,Kubernetes 就会自动创建一个新的 Pod 来代替它。
而容器产生的数据,会随着 Pod 消亡而自动消失。
为了实现 Pod 内数据的存储管理,Kubernetes 引入了两个 API 资源:Persistent Volume(持久卷,以下简称 PV)和 Persistent Volume Claim(持久卷申请,以下简称 PVC)。
PV 是 Kubernetes 集群中的一种网络存储实现,跟 Node 一样,也是属于集群的资源。
PV 跟 Docker 里的 Volume(卷)类似,不过会有独立于 Pod 的生命周期。
使用 kubectl get pv 查看列表:

而 PVC 是用户的一个请求,跟 Pod 类似。Pod 消费 Node 的资源,PVC 消费 PV 的资源。

Pod 能够申请特定的资源(CPU 和内存);PVC 能够申请特定的尺寸和访问模式,例如可以加载一个读写实例或者多个只读实例,(就是上图 kubectl get pvc 返回结果的 Access Mode 这一列的值 RWO, ROX 等等)而无须感知这些实例背后具体的存储实现。
我们来看一个具体的 PVC 实例,名称为 nginx-pvc:
kind: PersistentVolumeClaim apiVersion: v1 metadata: name: nginx-pvc spec: storageClassName: default accessModes: - ReadOnlyMany resources: requests: storage: 1Gi

使用命令 kubectl create -f pvc.yaml 创建这个 yaml 文件定义的 persistent volume claim:

然后定义一个 pod,消费这个名为 nginx-pvc 的 persistent volume claim:


使用 kubectl describe pvc nginx-pvc 查看这个 persistent volume claim 对应生成的 persistent volume:


现在我用命令 kubectl cp train.jpg nginx-storage-pod:/usr/share/nginx/html 将两个文件 train.jpg 和 index.html 文件拷贝到 pod 内部文件路径/usr/share/nginx/html 下面:

现在切换到 nginx-storage-pod pod 里,在/usr/share/nginx/html 目录下果然发现了这两个文件:

接下来我定义了另一个 pod,同样适用 nginx-pvc 这个 PVC:

创建完这个 pod 之后,then kubectl exec -ti another ash 进入 pod 内部/usr/share/nginx/html,同样发现了 index.html 和 train.jpg.

这个例子说明 persistent volume claim 能够用于在多个 pod 间共享持久化数据。要获取更多 Jerry 的原创文章,请关注公众号"汪子熙":

版权声明: 本文为 InfoQ 作者【Jerry Wang】的原创文章。
原文链接:【http://xie.infoq.cn/article/bc373ca2e2f9dc128df01617a】。文章转载请联系作者。
评论