nginx - nginx 反向代理可访问多个 docker 容器

标签 nginx docker reverse-proxy

我想在一个只能通过一个域访问的主机 VM 上运行多个 docker 容器。我想使用请求 url 来区分容器。
为了实现这一点,我试图将 nginx 服务器设置为反向代理,并在容器中运行它,同时监听端口 80。

假设我有两个容器在端口 3000 和 4000 上运行。
路由如下:

docker-host.example.com/3000 -> this will access container exposing port 3000
docker-host.example.com/4000 -> this will access container exposing port 4000

问题是我目前正在尝试为这种反向代理定义静态规则。
它在没有任何位置的情况下工作正常:
upstream application {
    server <docker container>:3000;
}

server {
        listen 80;

        location / {
            proxy_pass_header  Server;
            proxy_set_header   Host $http_host;
            proxy_redirect     off;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Scheme $scheme;
            proxy_pass         http://application/;
        }
}

但是当我添加端口位置并尝试使用 localhost:{nginx port}/3000/访问它时
upstream application {
    server <docker container>:3000;
}

server {
        listen 80;

        location /3000/ {
            proxy_pass_header  Server;
            proxy_set_header   Host $http_host;
            proxy_redirect     off;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Scheme $scheme;
            proxy_pass         http://application/3000/;
        }
}

似乎正确请求了第一个资源(主 html),但缺少任何其他依赖资源(例如该站点所需的 js 或 css)。
如果我检查日志中对这些资源的请求:
09:19:20 [error] 5#5: *1 open() "/etc/nginx/html/public/css/fonts.min.css" failed (2: No such file or directory), client: 172.17.0.1, server: , request: "GET /public/css/fonts.min.css HTTP/1.1", host: "localhost:8455", referrer:"http://localhost:8455/3000/"

所以请求 url 是 http://localhost:8455/public/css/fonts.min.css

而不是 http://localhost:8455/3000/public/css/fonts.min.css

我可以问你任何建议吗?这种情况可能吗?

最佳答案

您可以为每个端口选择一个 docker 容器,例如:

  • http://example.com:4000/css/fonts.min.css
  • http://example.com:3000/css/fonts.min.css

  • 但是我更喜欢另一种方法,因为我认为它更清晰,通过域名访问 docker 容器,例如:
  • http://a.example.com/css/fonts.min.css
  • http://b.example.com/css/fonts.min.css

  • 无论你选择哪个,github中有一个项目可以帮你实现docker多容器反向代理:https://github.com/jwilder/nginx-proxy

    我在类似的场景中使用 docker-compose 编写了一个示例:http://carlosvin.github.io/posts/reverse-proxy-multidomain-docker/

    关于nginx - nginx 反向代理可访问多个 docker 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43654135/

    相关文章:

    php - PHP-fpm+nginx 没有可用的环境变量

    iis - 使用反向代理的客户端证书身份验证

    django - 为什么 Django Static Generator 和 Nginx 没有给我超快的速度?

    linux - 只有部分本地构建的 Docker 镜像无法在远程服务器上运行(错误 : "No command specified")

    Docker 容器不会运行 : "file already closed" error

    docker - 通过多个Docker容器监听同一端口

    reverse-proxy - traefik 可以重写重定向响应的位置 header 吗 (302)

    nginx - SSL 握手失败

    nginx - 如何增加 gitlab CE lfs 文件大小限制以避免出现 500 服务器错误?

    express - 使用 aws elastic beantalk 将非 www 重定向到 www