【问题标题】:How to make ngnix docker containers accessible through proxy?如何使 nginx docker 容器可以通过代理访问?
【发布时间】:2018-05-18 15:18:51
【问题描述】:

假设我有三个带有 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 bad gateway 错误。是否与我暴露的端口和 VIRTUAL_PORT 有关?

提前致谢。

【问题讨论】:

  • 您可以尝试将配置文件分别编辑为proxy_pass http://localhost:8181/example01; proxy_pass http://localhost:8282/example02;

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


【解决方案1】:

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

$ ifconfig

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

配置:

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 工具docker-compose。假设您熟悉它是什么(底部的 doc refs),您可以编写一个这样的 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

你会配置“主” nginx 来使用创建的链接,如下所示:

配置:

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

【讨论】:

  • 抱歉回复晚了。谢谢!您介意详细说明容器的链接吗?我是新手
  • 编辑了答案
  • 谢谢!这非常有帮助。我只是在学习这些东西。
  • 很高兴听到它有帮助。保重 ;)
猜你喜欢
  • 2017-09-25
  • 2020-02-26
  • 1970-01-01
  • 2019-07-18
  • 2016-07-04
  • 2022-11-02
  • 2018-03-27
  • 2017-11-13
  • 1970-01-01
相关资源
最近更新 更多