[英]NGINX reverse proxy not working for .NET core webAPI running in Docker
[英]Nginx reverse proxy to .Net Core API in docker
我在嘗試使以下內容在Docker中工作時遇到麻煩
我想要的是,當用戶請求http://localhost/api
NGINX將代理反向到在另一個容器中運行的.Net Core API。
容器主機:Windows
容器1:NGINX
docker文件
FROM nginx
COPY ./nginx.conf /etc/nginx/nginx.conf
nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
server {
location /api1 {
proxy_pass http://api;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
容器2:.Net Core API
簡單無用-容器中端口80上暴露的API
然后是docker-compose.yml
docker-compose.yml
version: '3'
services:
api1:
image: api1
build:
context: ./Api1
dockerfile: Dockerfile
ports:
- "5010:80"
nginx:
image: vc-nginx
build:
context: ./infra/nginx
dockerfile: Dockerfile
ports:
- "5000:80"
閱讀Docker文檔指出:
鏈接允許您定義額外的別名,通過該別名可以從另一個服務訪問服務。 不需要它們就可以使服務進行通信-默認情況下,任何服務都可以使用該服務的名稱到達任何其他服務。
因此,由於我的API服務稱為api1
,因此我在nginx.conf
文件中簡單地將此引用作為反向代理配置的一部分:
proxy_pass http://api1;
當我輸入http:\\\\localhost\\api
時出現錯誤,這是404錯誤。
有沒有辦法解決這個問題?
問題是nginx位置配置。
404錯誤是正確的,因為您的配置是將請求從http://localhost/api/some-resource
代理到缺少的資源,因為您的映射是針對/api1
路徑的,而您要的是/api
。
因此,您只應將位置更改為/api
。
請記住,對http://localhost/api
請求將被代理到http://api1/api
(保留路徑)。 如果您的后端配置為使用前綴路徑公開api,則可以,否則,您將收到另一個404(這次來自您的服務)。 為避免這種情況,您應在使用以下規則代理請求之前重寫路徑:
# transform /api/some-resource/1 to /some-resource/1
rewrite /api/(.*) /$1 break;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.