如何使用 NGINX 将请求转发到 Docker 微服务

How to use NGINX to forward the request to Docker Microservice

我想使用 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;
            }


        }


    }

Docker 文件

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/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 将请求转发到管理门户

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;
#            }
        }