如何使用从 nginx.conf 中的部署文件传递的环境变量

How can I use environment variables passed from deployment file in nginx.conf

下面是我的 docker 文件中的逻辑。 我正在使用 nginx 构建应用程序。

FROM node:14-alpine as builder

COPY package.json ./
RUN npm install && mkdir /app && mv ./node_modules ./app
WORKDIR /app

COPY . .

RUN npm run build


FROM nginx:1.16.0-alpine
COPY --from=builder /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d

EXPOSE 3000

CMD ["nginx", "-g", "daemon off;"]

下面是 nginx.conf 文件

server {
   listen 3000;
      
   location / {
     root /usr/share/nginx/html;
     index index.html index.htm;
     try_files $uri $uri/ /index.html =404;
   }
  
   location /api {
    #  rewrite /api/api(.*) / break;
     proxy_pass http://${backend_host}:${backend_port}/api;
   }
      
   include /etc/nginx/extra-conf.d/*.conf;
}

backend_host 和 backend_port 在 proxy_pass URL 将在使用部署文件部署图像时提供。

这可能吗? 如果没有,还有其他方法吗?

如果你想动态挂载 nginx.conf 我建议你使用 config map 和你的 deployment.yaml

所以这样你就可以多次 re-use 你的 docker 图像而不重新创建它并通过 config 映射 来更新它。

您 docker 文件将

FROM node:14-alpine as builder
COPY package.json ./
RUN npm install && mkdir /app && mv ./node_modules ./app
WORKDIR /app
COPY . .
RUN npm run build


FROM nginx:1.16.0-alpine
COPY --from=builder /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
EXPOSE 3000
CMD ["nginx", "-g", "daemon off;"]

配置映射示例

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  default.conf: |-
    server {
            listen 80 default_server;
            root /var/www/html;
            server_name  _;
            index index.php;
            location / {
                try_files $uri $uri/ /index.php?$args;
            }
            location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param   PATH_INFO       $fastcgi_path_info;
                fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
            }
        }

将配置映射装载到部署

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app
  labels:
    app: app
spec:
  selector:
    matchLabels:
      app: app
  replicas: 1
  template:
    metadata:
      labels:
        app: app
    spec:
      containers:
        - name: app
          image: app-image
          ports:
          - containerPort: 80
          volumeMounts:
            - name: nginx-config
              mountPath: /etc/nginx/nginx.conf
              subPath: nginx.conf
      volumes:
        - name: nginx-config
          configMap:
            name: confnginx

有关详细信息,请阅读:https://blog.meain.io/2020/dynamic-reverse-proxy-kubernetes/