我正在尝试构建一个简单的 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
模块 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
最佳答案
我可以在您的配置中找到 2 个问题:
upstream client {
server client;
}
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/