0x1、背景

在梳理线上业务过程发现,Pod的配置文件中containerPort参数配置错误也能正常通信;在接触k8s时间里一直以为containerPort参数必须设置才能使容器内服务被外部访问,通过一系列实验发现containerPort这个参数有些鸡肋。

官方解释containerPort参数:

1
2
3
4
5
List of ports to expose from the container. Exposing a port here gives the system additional 
information about the network connections a container uses, but is primarily informational.
Not specifying a port here DOES NOT prevent that port from being exposed.
Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from the network.
Cannot be updated.

根据文档描述可以看出containerPort参数是用来暴露容器端口服务,但后面描述凡是监听0.0.0.0地址的端口都可以被访问即使没有设置containerPort参数

0x2、验证

为了验证文档的正确性,通过配置k8s的v1.20版本环境测试一下;这里采用redis设计实验场景

场景一

  • 配置redis server的监听地址为0.0.0.0
  • Pod文件不使用containerPort参数

redis-server配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
apiVersion: v1
kind: Service
metadata:
name: redis
spec:
ports:
- name: tcp
port: 6379
selector:
component: redis-server
type: ClusterIP
---
apiVersion: v1
data:
redis.conf: |
bind 0.0.0.0
port 6379
kind: ConfigMap
metadata:
name: redis
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: &name redis-server
spec:
replicas: 1
selector:
matchLabels:
component: *name
template:
metadata:
labels:
component: *name
spec:
containers:
- command: ['sh', '-c', 'redis-server /conf/redis.conf']
image: redis:6.0
name: *name
volumeMounts:
- mountPath: /conf
name: config
volumes:
- name: config
configMap:
name: redis

场景二

  • 配置redis server的监听地址为127.0.0.1
  • Pod文件使用containerPort参数

根据实验操作结果,场景一是可以被访问,验证了文档中描述监听0.0.0.0模式下不受containerPort配置限制; 场景二中是不能被访问,即使配置了containerPort参数。

通过上述简单实验验证,containerPort功能在实际业务中比较鸡肋;k8s网络组件比较复杂,后续补上相关逻辑实现部分…

0x3、参考

评论