在 Kubernetes 中开启容器内文件系统的只读功能,可以通过设置securityContext.readOnlyRootFilesystem
参数实现。以下是具体的配置方法和注意事项:
1. 基本配置示例
在 Pod 或容器的securityContext
中设置readOnlyRootFilesystem: true
:
apiVersion: v1
kind: Pod
metadata:
name: read-only-pod
spec:
containers:
- name: my-app
image: nginx:1.14.2
securityContext:
readOnlyRootFilesystem: true # 开启只读文件系统
ports:
- containerPort: 80
volumeMounts:
- name: tmp-volume # 为需要写权限的目录挂载临时卷
mountPath: /tmp
volumes:
- name: tmp-volume
emptyDir: {} # 使用emptyDir提供可写临时空间
2. 关键配置说明
(1) 只读文件系统设置
readOnlyRootFilesystem: true
:将容器的根文件系统设置为只读。- 生效范围:影响容器内的所有文件系统挂载点(除了显式挂载的卷)。
(2) 保留可写目录
容器运行时通常需要以下目录可写,需通过卷挂载:
/tmp
:临时文件存储。/var/run
:Unix 套接字和 PID 文件。- 日志目录:如
/var/log
(如果应用直接写日志到文件系统)。
示例:
containers:
- name: my-app
securityContext:
readOnlyRootFilesystem: true
volumeMounts:
- name: tmp-volume
mountPath: /tmp
- name: var-run
mountPath: /var/run
volumes:
- name: tmp-volume
emptyDir: {}
- name: var-run
emptyDir: {}
3. 特殊场景处理
(1) 应用需要写入配置文件
如果应用需要修改配置文件(如/etc/nginx/nginx.conf
),可通过以下方式:
-
使用 ConfigMap 挂载配置文件:
volumeMounts: - name: config-volume mountPath: /etc/nginx/nginx.conf subPath: nginx.conf volumes: - name: config-volume configMap: name: nginx-config
-
初始化容器(Init Container)预处理:
initContainers: - name: config-init image: busybox command: ['sh', '-c', 'cp /config/nginx.conf /work-dir/'] volumeMounts: - name: config-volume mountPath: /config - name: work-volume mountPath: /work-dir containers: - name: nginx volumeMounts: - name: work-volume mountPath: /etc/nginx/nginx.conf subPath: nginx.conf
(2) 日志处理
避免应用直接写日志到文件系统,推荐使用以下方式:
- 标准输出 / 错误输出:容器内应用将日志输出到
stdout
/stderr
,由 Kubernetes 收集。 - 日志代理:如 Fluentd、Filebeat 作为 Sidecar 容器收集日志。
4. 安全增强配置
结合其他安全参数提升容器安全性:
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true # 以非root用户运行
allowPrivilegeEscalation: false # 禁止特权升级
capabilities:
drop:
- ALL # 移除所有能力
add:
- NET_BIND_SERVICE # 仅添加必要能力
5. 验证只读文件系统
部署 Pod 后,可通过以下方式验证:
# 进入容器
kubectl exec -it read-only-pod -- /bin/sh
# 尝试创建文件(应失败)
touch /test.txt # 报错:Read-only file system
# 检查/tmp目录(应可写)
touch /tmp/test.txt # 成功
6. 注意事项
-
应用兼容性:
- 确保应用不依赖于写入根文件系统(如临时文件、缓存)。
- 某些应用(如数据库)可能需要大量写操作,需谨慎配置。
-
卷挂载覆盖:
- 显式挂载的卷(如
emptyDir
、hostPath
、PersistentVolumeClaim
)不受只读限制。
- 显式挂载的卷(如
-
Kubernetes 版本:
readOnlyRootFilesystem
在 Kubernetes 1.0 + 版本支持。
7. 实战案例:Nginx 只读配置
apiVersion: v1
kind: Pod
metadata:
name: nginx-readonly
spec:
containers:
- name: nginx
image: nginx:1.14.2
securityContext:
readOnlyRootFilesystem: true
runAsNonRoot: true
ports:
- containerPort: 80
volumeMounts:
- name: tmp-volume
mountPath: /tmp
- name: var-run
mountPath: /var/run
- name: nginx-config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
volumes:
- name: tmp-volume
emptyDir: {}
- name: var-run
emptyDir: {}
- name: nginx-config
configMap:
name: nginx-config # 需提前创建ConfigMap
通过上述配置,Nginx 容器的文件系统将变为只读,同时确保必要目录可写,提升了容器的安全性。