簡體   English   中英

在 Docker 上使用 Nginx 重定向端口

[英]Redirecting ports with Nginx on Docker

我正在嘗試構建一個簡單的 Docker 項目,其中只有幾個容器由一個 Nginx 服務器連接。 對於我的全棧項目來說,基本上它是更簡單的模擬。 我在將一個容器主端口重定向到另一個項目中的路徑時遇到問題。

項目包含兩個模塊和一個docker-compose.yml文件。 預期行為是在 http://localhost 上看到一個 html 網站,在 http://localhost/api 上看到另一個。 當我運行項目時,我在 http://localhost 上看到了預期的結果,但要訪問其他站點,我需要轉到 http://localhost:4000 。 如何解決?

項目文件(源代碼在這里

模塊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

模塊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

我可以在您的配置中找到兩個問題:

  1. 您正在重定向到客戶端容器上的端口 4000,您不需要這樣做,因為端口 4000 僅與您的主機相關。 因此上游配置應如下所示:
upstream client {
    server client;
}
  1. 您正在重定向到客戶端容器上的 /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/。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM