简体   繁体   中英

Use docker-compose service names in Nginx config

I have an application with 4 services. One of them is Nginx which will act as a proxy. I use docker compose to run the services. In nginx when I specify a path and where to proxy I want to be able to use the service name. 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:

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. I specify it inside nginx docker image:

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:

[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. What am I doing wrong/misunderstanding?

The issue is that nginx does not read ENV variables.

see https://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

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.

the last line is modified to do a substitution using your ENV variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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