简体   繁体   English

在 Nginx 配置中使用 docker-compose 服务名称

[英]Use docker-compose service names in Nginx config

I have an application with 4 services.我有一个包含 4 项服务的应用程序。 One of them is Nginx which will act as a proxy.其中之一是 Nginx,它将充当代理。 I use docker compose to run the services.我使用 docker compose 来运行服务。 In nginx when I specify a path and where to proxy I want to be able to use the service name.在 nginx 中,当我指定路径和代理位置时,我希望能够使用服务名称。 This is what I have done so far.这是我到目前为止所做的。

version: '3'
services:
  go_app:
    image: go_app
    depends_on: 
      - mysql
    ports: 
      - "8000:8000"

  mysql:
    image: mysql_db
    ports: 
      - "3306:3306"

  flask_app:
    image: flask_app
    ports: 
      - "8080:8080"

  nginx:
    image: nginx_app
    ports: 
      - "80:80"
    depends_on: 
      - mysql
      - flask_app
      - go_app

With the above I create all services.通过以上内容,我创建了所有服务。 They all work on their respective ports.他们都在各自的端口上工作。 I want Nginx to listen on port 80 and proxy as defined in the config:我希望 Nginx 监听配置中定义的端口 80 和代理:

server {
listen 0.0.0.0:80;
server_name localhost;

location / {
  proxy_pass http://${FLASK_APP}:8080/;
  }
}

You may ask where does FLASK_APP come from.你可能会问 FLASK_APP 是从哪里来的。 I specify it inside nginx docker image:我在 nginx docker 图像中指定它:

FROM nginx

ENV FLASK_APP=flask_app
RUN rm /etc/nginx/conf.d/default.conf
COPY config/default.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Nginx container keeps failing with the following error: Nginx 容器不断失败,并出现以下错误:

[emerg] 1#1: unknown "flask_app" variable
nginx: [emerg] unknown "flask_app" variable

The way I understand docker compose, flask_app should resolve as the flask_app service.我理解 docker 撰写的方式, flask_app应该解析为 flask_app 服务。 What am I doing wrong/misunderstanding?我在做什么错/误解?

The issue is that nginx does not read ENV variables.问题是 nginx 不读取 ENV 变量。

see https://github.com/docker-library/docs/tree/master/nginx#using-environment-variables-in-nginx-configurationhttps://github.com/docker-library/docs/tree/master/nginx#using-environment-variables-in-nginx-configuration

a solution: you can modify you dockerfile for nginx with this一个解决方案:你可以用这个修改你的 dockerfile 为nginx

FROM nginx
ENV FLASK_APP=flask_app
RUN rm /etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d/default.template
EXPOSE 80
CMD ["/bin/bash","-c","envsubst < /etc/nginx/conf.d/default.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"]

the COPY command is modified to copy you configuration as a template. COPY命令被修改为将您的配置复制为模板。

the last line is modified to do a substitution using your ENV variables.最后一行被修改为使用您的 ENV 变量进行替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM