积极努力将配置注入到运行在Kubernetes上的nginx中

nginx的官方Docker容器镜像提供了在/docker-entrypoint.d/目录下放置脚本或者其他shell脚本来执行的功能。

 

但是目前的实现情况是在文件实体被替换为符号链接时会被忽略。我们目前使用的Kubernetes实现k0s将ConfigMap挂载为卷时会创建符号链接,因此无法阅读。

 

所以我向原厂提出了公关建议,但这只是一方面,在目前的情况下,我们应该怎么做还需要试试看。

我想要做的事情

为了避免删除default.conf文件导致nginx无法正常工作,我们需要在/etc/nginx/conf.d/中挂载ConfigMap,同时保留/etc/nginx/conf.d/中的内容,并添加新的配置文件。

你怎么了?

/etc/nginx/conf.d/の中身を保存するemptyDirボリュームを作る

initコンテナで/etc/nginx/conf.d/の中身を組み立てる。

nginxコンテナを起動して/etc/nginx/conf.d/をemptyDirボリュームにコピる
Volume mountしたConfigMapの中身をemptyDirボリュームにコピるbusyboxコンテナを起動

前段で作ったemptyDirボリュームを/etc/nginx/conf.d/にマウントしてnginxを起動する。

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: nginx
  name: nginx
  namespace: sample
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.23.3
        name: nginx
        ports:
        - containerPort: 80
          name: http
        volumeMounts:
        - name: contents
          mountPath: /usr/share/nginx/html
          readOnly: true
        - name: confd
          mountPath: /etc/nginx/conf.d
      initContainers:
      - name: copy configmap
        image: busybox:1.34.1
        command:
        - cp
        - -r # copy directories recursively
        - -L # always follow symbolic links in SOURCE
        - -T # treat DEST as a normal file
        - /config/
        - /confd/
        volumeMounts:
        - name: config
          mountPath: /config
        - name: confd
          mountPath: /confd
      - name: copy nginx conf
        image: nginx:1.23.3
        command:
        - cp
        - -r # copy directories recursively
        - -L # always follow symbolic links in SOURCE
        - -T # treat DEST as a normal file
        - /etc/nginx/conf.d/
        - /confd/
        volumeMounts:
        - name: confd
          mountPath: /confd
      volumes:
      - name: confd
        emptyDir: {}
      - name: contents
        persistentVolumeClaim:
          claimName: nginx-contents-pvc
      - name: config
        configMap:
          name: nginx-config

请留意以下事项

在使用init容器进行cp操作时,如果不加-T参数,会生成意外的目录,导致我陷入困境。

找到没有跟随”find”的”-follow”的部分。default.conf只包含了一个简单的http服务器配置,通过80/tcp进行监听,并返回/usr/share/nginx/html的内容,所以如果要写入包括这个配置在内的新配置也是可以覆盖的。

如果能够将放置了shell脚本的ConfigMap使用0744挂载并执行在/docker-entrypoint.d/,那就可以解决问题。

使用”cp”命令来复制目标目录的存在/不存在 – Qiita。