如何使用NGINX将请求转发到Docker Microservice

时间:2018-07-04 07:22:29

标签: docker nginx nginx-location nginx-reverse-proxy

我想使用NGINX作为反向代理将请求转发给微服务。 NGINX和微服务都托管在docker容器上。

下面是我的nginx.conf文件

    worker_processes 1;

    events { worker_connections 1024; }

    #test

    http {

        sendfile on;

        # upstream docker-nginx {
        #     server nginx:80;
        # }

        upstream admin-portal {
            # server admin-portal:9006;
            server xx.xx.xx.xx:9006;
            # server localhost:9006;

        }

server {
            listen 8080;

            location / {
                proxy_pass         http://admin-portal;
                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;
            }


        }


    }

Dockerfile

FROM nginx
RUN apt-get update && apt-get install -y \
curl 
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 8080

docker-compose.yml

version: '3'
services:
  nginx:
    restart: always
    build: ../../conf/
    volumes:
    - ./mysite.template:/etc/nginx/conf.d/mysite.template
    ports:
    - "8080:8080"
    networks:
      - cloud


networks:
  cloud:
   driver: bridge
  • 我可以通过 localhost:8080
  • 访问nginx主页
  • admin-portal是在9006端口上运行的微服务

但是,如果我执行 localhost:8080 / admin-portal / ,我将遇到错误

nginx_1 | 2018/07/04 07:08:17 [error] 7#7: *1 "/usr/share/nginx/html/admin-portal/index.html" is not found (2: No such file or directory), client: xx.xx.xx.xx, server: your-domain.com, request: "GET /admin-portal/ HTTP/1.1", host: "xx.xx.xx.xx:8080" nginx_1 | 2018/07/04 07:08:17 [error] 7#7: *1 open() "/usr/share/nginx/html/404.html" failed (2: No such file or directory), client: xx.xx.xx.xx, server: your-domain.com, request: "GET /admin-portal/ HTTP/1.1", host: "xx.xx.xx.xx:8080" nginx_1 | xx.xx.xx.xx - - [04/Jul/2018:07:08:17 +0000] "GET /admin-portal/ HTTP/1.1" 404 170 "-" "curl/7.47.0" admin-portal/

请提出我需要做些什么更改才能使用nginx将请求转发到admin-portal

1 个答案:

答案 0 :(得分:1)

upstream admin-portal {
    server 127.0.0.1:9006;
}

应该是:

upstream admin-portal {
    server 172.17.0.1:9006;
}

使用172.17.0.1是容器的IP地址网关。

或者docker inspect containermicroservice_id然后获取该容器的IP地址。

 upstream admin-portal {
    server ipaddressofmicroservicecontainer:9006;
}

将服务器的IP地址放入

        server_name    localhost ipaddressofserver www.example.com;

然后访问http://ipaddressofserver:8080/admin-portal

注释此部分:

#server {
#            listen       8080;
#            server_name     your-domain.com www.your-domain.com;
#            root   /usr/share/nginx/html;
#            index  index.html index.htm;

#            error_page  404              /404.html;
#            error_page   500 502 503 504  /50x.html;
#            location = /50x.html {
#                root   html;
#            }
        }