docker - 在 Docker 上使用 Nginx 重定向端口

标签 docker nginx

我正在尝试构建一个简单的 Docker 项目,其中您有几个由一个 Nginx 服务器连接的容器。基本上,对于我的全栈项目来说,它是更简单的模拟。我在将一个容器主端口重定向到另一个项目中的路径时遇到问题。
项目包含两个模块和一个docker-compose.yml文件。预期的行为是在 http://localhost 上看到一个 html 网站,在 http://localhost/api 上看到另一个。当我运行项目时,我在 http://localhost 上看到了预期的结果,但是要访问另一个站点,我需要访问 http://localhost:4000 。如何解决?
项目文件 (source code here)
模块 Client索引.html:

this is website you should see under /api
Dockerfile:
FROM node:14.2.0-alpine3.11 as build
WORKDIR /app
COPY . .
FROM nginx as runtime
COPY --from=build /app/ /usr/share/nginx/html
EXPOSE 80
模块 Nginxindex.html :
<p>this is index file. You should be able to go to <a href="/api">/api route</a></p>
default.conf :
upstream client {
    server client:4000;
}

server {
    listen 80;

    location /api {
        proxy_pass http://client;
    }

    location / {
        root /usr/share/nginx/html;
    }
}
Dockerfile:
FROM nginx
COPY ./default.conf /etc/nginx/conf.d/default.conf 
COPY index.html /usr/share/nginx/html
主目录docker-compose.yml文件:
version: "3"
services: 
    client: 
        build: Client
        ports:
            - 4000:80
    nginx:
        build: Nginx
        ports: 
            - 80:80
        restart: always
        depends_on: 
            - client

最佳答案

我可以在您的配置中找到 2 个问题:

  • 您正在重定向到客户端容器上的端口 4000,您不需要这样做,因为端口 4000 仅与您的主机相关。所以上游配置应该如下所示:
  • upstream client {
        server client;
    }
    
  • 您正在重定向到客户端容器上的/api,但您的客户端容器在/处提供内容。您应该将您的 default.conf 更改为如下所示(注意尾部的斜杠!):
  • upstream client {
        server client;
    }
    
    server {
        listen 80;
    
        location /api/ {
            proxy_pass http://client/;
        }
    
        location / {
            root /usr/share/nginx/html;
        }
    }
    
    使用此配置,您可以输入 http://localhost/api/以访问您的客户端容器。如果您希望 http://localhost/api 正常工作,您可以在 default.conf 中将/api 重定向到/api/。

    关于docker - 在 Docker 上使用 Nginx 重定向端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64151523/

    相关文章:

    nginx - 使用 nginx,如何在从另一台服务器返回的页面上运行 SSI?

    magento - 如何在 ubuntu localhost 上使用 magento 配置 nginx

    git - 无法在 GitLab CI/CD 中的作业之间传递工件

    linux - kubernetes:Docker请求和分配的内容之间的区别

    c++ - 在windows docker容器中编译Qt5项目

    python - 对于 SSL 和非 SSL 配置,如何使用子域将 nginx 正确设置为 gunicorn 和 flask 的反向代理?

    service - 如何在 Docker 后台启动 railo 服务

    docker - envoy v3 关于 typed_config http 连接管理器的非法映射值

    python - 如何使 environ ['PATH_INFO' ] 在我的 nginx + uwsgi 环境中可用?

    nginx - 简单的 nginx 反向代理似乎剥离了一些 header