問題引入
我們在使用 AWS [EFS]作為k8s持久卷時,時常會碰到chown: changing ownership of 'xxxx': Operation not permitted這樣的權限問題。
SecurityContext
Security Context 的目的是限制不可信容器的行為,保護系統和其他容器不受其影響。
Kubernetes 提供了三種配置 Security Context 的方法:
- Container-level Security Context:僅應用到指定的容器
- Pod-level Security Context:應用到 Pod 内所有容器以及 Volume
- Pod Security Policies(PSP):應用到叢集内部所有 Pod 以及 Volume
最佳實踐
我們這裡使用 k8s 部署一個單節點postgresql,持久卷使用AWS EFS,關于 efs 的建立可參考AWS官方文檔,這裡不再詳述了。
部署efs
根據官方文檔,我們建立一個檔案系統,如下:
部署單節點postgres
主要檔案:configmap、pvc、deployment
configmap 配置檔案
postgres-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: postgres-authelia-config
namespace: middle
labels:
app: postgres
data:
POSTGRES_DB: authelia
POSTGRES_USER: authelia
POSTGRES_PASSWORD: test#888
pvc 配置檔案
postgres-pvc.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: postgres-authelia-pvc
namespace: middle
labels:
app: postgres
annotations:
volume.beta.kubernetes.io/storage-class: "prometheus-data-db"
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 1Gi
deployment 檔案
apiVersion: apps/v1
kind: Deployment
metadata:
name: postgres-authelia
namespace: middle
spec:
strategy:
type: Recreate
selector:
matchLabels:
app: postgres
replicas: 1
template:
metadata:
labels:
app: postgres
spec:
containers:
- name: postgres-authelia
image: postgres:11.7
imagePullPolicy: "IfNotPresent"
## 注意下這裡的配置
securityContext:
runAsUser: 50015
runAsGroup: 50015
ports:
- containerPort: 5432
envFrom:
- configMapRef:
name: postgres-authelia-config
volumeMounts:
- mountPath: /var/lib/postgresql/data
name: postgredb
volumes:
- name: postgredb
persistentVolumeClaim:
claimName: postgres-authelia-pvc
---
apiVersion: v1
kind: Service
metadata:
name: postgres-authelia
namespace: middle
labels:
app: postgres
spec:
type: ClusterIP
ports:
- port: 5432
protocol: TCP
selector:
app: postgres
部署 yaml
- kubectl apply -f postgres-pvc.yaml
- kubectl apply -f postgres-configmap.yaml
- kubectl apply -f postgres-deploy-efs.yaml
檢視服務狀态
securityContext:
runAsUser: 50015
runAsGroup: 50015
- 如果不增加如上内容,會報chown: changing ownership of '/var/lib/postgresql/data': Operation not permitted權限錯誤。
- 50015是從efs接入點得到的POSIX 使用者資訊