将nginx.conf添加到Kubernetes集群中

31

如何将 nginx.conf 配置文件传递给运行在 Kubernetes 集群内的 nginx 实例?

2个回答

58
您可以创建一个 ConfigMap 对象,然后将其挂载为文件,以便在需要的位置使用它们:
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  nginx.conf: |
    your config
    comes here
    like this
  other.conf: |
    second file
    contents

并且在您的Pod规范中:

spec:
  containers:
    - name: nginx
      image: nginx
      volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx/nginx.conf
          subPath: nginx.conf
        - name: other.conf
          mountPath: /etc/nginx/other.conf
          subPath: other.conf
  volumes:
    - name: nginx-config
      configMap:
        name: nginx-config

(注意在mountPath中文件名的重复以及使用完全相同的subPath;与绑定挂载文件相同。)

有关ConfigMap的更多信息,请参见: https://kubernetes.io/docs/user-guide/configmap/

注意:使用ConfigMap作为subPath卷的容器将不会收到ConfigMap的更新。


16

我还没有找到一种好的方法来转义ConfigMap中的nginx配置内容。对我而言,最好的选择是使用文件创建ConfigMap

将以下内容保存为./data/nginx.conf

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

现在创建configMap: kubectl create configmap confnginx --from-file=./data/nginx.conf

将以下部署和Pod的yaml保存为nginx.yaml

apiVersion: apps/v1 # for versions before 1.9.0 use apps/v1beta2
kind: Deployment
metadata:
  name: nginx
  labels:
    app: nginx     
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1 # tells deployment to run 2 pods matching the template
  template: # create pods using pod definition in this template
    metadata:
      # unlike pod-nginx.yaml, the name is not included in the meta data as a unique name is
      # generated from the deployment name
      labels:
        app: nginx     
    spec:
      containers:
        - name: nginx
          image: nginx:alpine
          ports:
          - containerPort: 80        
          volumeMounts:
            - name: nginx-config
              mountPath: /etc/nginx/nginx.conf
              subPath: nginx.conf
      volumes:
        - name: nginx-config
          configMap:
            name: confnginx

现在在k8中创建它

kubectl apply -f nginx.yaml

2
问题可能是由于你的nginx.conf中的注释所致。我遇到了同样的问题,但在删除所有带有“#”的行之后,配置映射按预期进行了。具体来说是你的tcp no push和gzip行。 - Lewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接