NGINX + Docker撰写路由问题

时间:2017-11-25 13:16:55

标签: nginx docker-compose uri microservices

我有一个docker compose文件,包含两个微服务,我想利用URI路由来处理CORS。这是我的撰写文件:

version: "3.1"
services:
  auth-api:
    image: xxxx/auth-api:latest
    restart: always
    depends_on:
      - "user-api"
  user-api:
    image: xxxx/user-api:latest
    restart: always
nginx:
    image: nginx
    restart: always
    ports:
      - "80:80"
    links:
      - "auth-api"
      - "user-api"
    volumes:
       - ./nginx:/etc/nginx

我想使用NGINX进行路由,但在尝试访问资源时遇到404或405的问题。我已经尝试了几种不同的配置,有一段时间NGINX说它在启动时找不到api端点我解决了所以我认为我的问题主要是路由配置。我希望这些请求为/auth/user

worker_processes 1;

events { worker_connections 1024; }

http {

    sendfile on;

    upstream auth-target {
      server auth-api:8080;
    }

    upstream user-target {
        server user-api:8080;
    }

    server {
        listen       80;

        location /auth {

            proxy_pass http://auth-target;

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }

        location /user {

            proxy_pass  http://user-target;

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }


    }

}

我对NGINX很陌生,所以我不确定我所做的事情是否正确。我还应该注意,两个API都有8080作为容器构建的一部分公开。

1 个答案:

答案 0 :(得分:0)

所以这是我的问题。路由工作正在进行,但我从我的服务中返回了404。这是因为Location路由与请求一起传递。所以最后我找到了答案:

https://serverfault.com/questions/562756/how-to-remove-the-path-with-an-nginx-proxy-pass

如果它指出您需要一个尾部斜杠以删除该位置,那么我的配置文件最终看起来像这样:

location /auth/ {

            proxy_pass http://auth-target/;

            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;
        }