Kubernetes/Docker/Docs/Nginx配置文件读取变量.md
offends 7a2f41e7d6
All checks were successful
continuous-integration/drone Build is passing
synchronization
2024-08-07 18:54:39 +08:00

1.1 KiB

本文作者:丁辉

Nginx配置文件读取变量

方法一使用 Envsubst 渲染替换环境变量

  1. 编辑 Dockerfile

    FROM nginx:alpine-slim
    
    COPY ./nginx.conf.template /etc/nginx/conf.d/nginx.conf.template
    
    ENV PROXY_SERVER=default
    
    CMD /bin/sh -c "envsubst '\$PROXY_SERVER \$SERVER_NAME' < /etc/nginx/conf.d/nginx.conf.template > /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'"
    
  2. 编辑 nginx.conf.template 文件

    vi nginx.conf.template
    

    内容如下

    server {
        listen       80;
        server_name  ${SERVER_NAME};
    
        location / {
            proxy_pass http://${PROXY_SERVER}:3080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
    
  3. 构建镜像

    docker build -t <name:tag> .
    
  4. 启动容器(指定变量)

    docker run -itd -e PROXY_SERVER=127.0.0.1 -e SERVER_NAME=localhost <name:tag>
    

方法二

查看此文档

Nginx镜像构建