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

标签 docker nginx

我在尝试让以下内容在Docker中工作时遇到麻烦

我想要的是,当用户请求http://localhost/api时,NGINX将代理反向到在另一个容器中运行的.Net Core 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 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文档指出:

Links allow you to define extra aliases by which a service is reachable from another service. They are not required to enable services to communicate - by default, any service can reach any other service at that service’s name.



因此,由于我的API服务称为api1,因此我在nginx.conf文件中简单地将此引用作为反向代理配置的一部分:
proxy_pass http://api1;
当我输入http:\\localhost\api时出现错误,出现404错误。

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

最佳答案

问题是nginx location配置。

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;

关于docker - Nginx反向代理到Docker中的.Net Core API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691705/

相关文章:

docker - 我应该如何为开发数据库构建 docker 镜像?

Nginx代理webrtc kurento媒体服务器配置

node.js - 使用 NginX 在 Digital Ocean 上托管多个 Node.js 应用程序

windows - 无法运行 Nginx 可执行文件

nginx + vueJS + 静态登陆页面

docker - 如何在 docker 容器中使用 nginx-proxy 通过 ssl 安全地运行 Gitlab

python - 作业不是由 APScheduler 的 BackgroundScheduler 执行的

php - Laravel API 路由在 Nginx 上获取 404

mysql - Docker 上的 Spring Boot 无法连接到 MySQL

docker - 如何在我的 CMD 脚本中设置环境变量