Nginx反向代理到Docker中的.Net Core API

我无法尝试在Docker中使用以下内容

我想要的是,当用户请求http://localhost/api然后NGINX反向代理到我的.Net核心API运行在另一个容器。

容器主机:Windows

容器1:NGINX

dockerfile

 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核心API

死简单 – API暴露在容器中的端口80上

然后是docker-compose.yml

泊坞窗,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文件中引用这个作为反向代理configuration的一部分:

proxy_pass http://api1;

有些东西是错误的,当我inputhttp:\\localhost\api我得到一个404错误。

有没有办法来解决这个问题?

问题是nginx的位置configuration。

404错误是正确的,因为你的configuration是从http://localhost/api/some-resource代理请求到一个缺less的资源,因为你的映射是/api1path,你问/api

所以你应该只改变位置/api ,它会工作。

请记住,对http://localhost/api请求将被代理到http://api1/api (path保留)。 如果您的后端configuration为使用前缀path公开api,则可以,否则您将收到另一个404(这次来自您的服务)。 为了避免这种情况,你应该在用这样的规则代理请求之前重写path:

 # transform /api/some-resource/1 to /some-resource/1 rewrite /api/(.*) /$1 break;