如何通过代理访问ngnix docker容器?

时间:2018-05-18 15:18:52

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

假设我有三个带nginx的docker容器。它们的暴露端口分别映射到8080,8181和8282。我想在8080上配置它代理/ example01和/ example02到其他两个应用程序的服务器。这是我的配置文件:

server {

    listen 80;
    server_name  localhost;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://localhost:8181/;
    }

    location /example02 {
        proxy_pass http://localhost:8282/;
    }
}

因此,如果我运行容器,则可以访问每个应用程序(http://localhost:8080http://localhost:8181http://localhost:8282)。

现在,我真的不明白为什么http://localhost:8080/example01http://localhost:8080/example02没有正确重定向。相反,我得到502错误的网关错误。它与我的暴露端口和VIRTUAL_PORT有关吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是因为容器网络范围。这些容器的localhost分别位于每个容器内 - 并且这不是您的端口映射到的位置。而是做:

$ ifconfig

在您的主机上找到您的本地IP地址并代理到主机的流量 - 这些端口已映射。

CONF:

server {

    listen 80;
    server_name  localhost;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://192.168.1.2:8181/;
    }

    location /example02 {
        proxy_pass http://192.168.1.2:8282/;
    }
}

其中192.168.1.2是您自己的计算机本地IP地址。

另一种方法是链接这些容器而不是通过localhost链接 - 但是您在链接定义中提供的别名。如果你选择这种方法,我可以详细说明。

- 使用关联方法进行编辑 -

为了关联您的服务,您需要使用泊坞窗工具docker-compose。假设你熟悉它是什么(底部的文档引用),你可以写一个这样的撰写文件:

first-nginx:
   build: first-nginx/
   ports:
      - 8080:80
   links:
      - second-nginx
      - third-nginx

second-nginx:
   build: second-nginx/
   ports:
      - 8081:80

third-nginx:
   build: third-nginx/
   ports:
      - 8082:80

放在项目的根目录中,如下所示:

root
  - first-nginx
    + nginx.conf
    + Dockerfile
    + some-other.files
  - second-nginx
    + some.files
    + another-nginx.conf
    + Dockerfile
  - third-nginx
    + some-nginx.conf
    + Dockerfile
  + docker-compose.yml

你要配置" main" nginx如此使用创建的链接:

CONF:

server {

    listen 80;

    location / {
        root    /usr/share/nginx/html/;
        index   index.html index.htm;
    }

    location /example01 {
        proxy_pass http://second-nginx/;
    }

    location /example02 {
        proxy_pass http://third-nginx/;
    }
}

请务必询问是否有任何不清楚的地方。

links ref

compose ref

相关问题