在Docker上使用Nginx重定向端口

4uqofj5v  于 5个月前  发布在  Nginx
关注(0)|答案(1)|浏览(61)

我正在尝试构建一个简单的Docker项目,其中您有几个容器由一个Nginx服务器加入。基本上,它对我的全栈项目进行了更简单的模拟。我在将一个容器主端口重定向到另一个项目中的路径时遇到了问题。
项目包含两个模块和一个docker-compose.yml文件。预期的行为是在http://localhost上看到一个html网站,在http://localhost/api上看到另一个。当我运行项目时,我在http://localhost上看到预期的结果,但要到达另一个网站,我需要去http://localhost:4000。如何修复它?

项目文件(source code here

模块Client

index.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

模块Nginx

index.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

r6hnlfcb

r6hnlfcb1#

我在您的配置中发现了两个问题:
1.您正在重定向到客户端容器上的端口4000,您不需要这样做,因为端口4000只与您的主机相关。因此上游配置应该如下所示:

upstream client {
    server client;
}

字符串
1.您正在重定向到客户端容器上的/API,但您的客户端容器在/处提供内容。您应该将默认的.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工作,您可以将/api重定向到默认. conf中的/api/。

相关问题