天天看点

K8S上使用EFS时权限故障处理

问题引入

我们在使用 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

根据官方文档,我们创建一个文件系统,如下:
K8S上使用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 用户信息