【问题标题】:Nginx cors setting not working in docker containerNginx cors 设置在 docker 容器中不起作用
【发布时间】:2019-07-15 20:21:11
【问题描述】:

我正在尝试通过 docker compose 在 linux 服务器上部署前端 (angular) 和后端 (.net core)。我在各自的文件中创建了两个 docker 文件。这是我的 docker.compos.yml 文件。

version: '3.4 
  volumes: 
   data:

services:
  api:
    build:
      context: .
      dockerfile: Backend/Dockerfile
    ports:
      - "5000:80"
    depends_on:
      - db
  web:
    build:
      context: .
      dockerfile: Frontend/Dockerfile
    ports:
     - "80:80"
    depends_on:
      - api
  db:
    image: postgres:latest
    volumes: 
     - data:/var/lib/postgresql/data
    environment:
      POSTGRES_USER: "postgres"
      POSTGRES_PASSWORD: "docker_Password"
      POSTGRES_DB: "database_name"
    ports:
      - "5432:5432"

我正在使用 nginx 映像来提供前端构建服务。这是带有基本设置的 default.conf 文件。

server {
    listen       80;
    server_name  localhost;
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }
}

通过上述配置,我运行 docker-compose up --build 并且能够看到我的登录页面(因为端口 80 已暴露,因此我的 url 是我的服务器 ip)。但是当我尝试登录时,它会向我在端口 5000 上运行的 api 服务发送一个 ajax 请求,并且我的前端在端口 80 上运行并尝试访问在端口 5000 上运行的服务时出现跨源错误。 我想做一些以 api 路径开头的请求(在我的例子中是 {server_ip}/api/login)应该重定向到 api 服务。 nginx中有什么有助于重定向请求的吗?

我也尝试在 default.conf 的位置块中添加以下行,但没有成功。

add_header 'Access-Control-Allow-Origin' '*';

add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'

;

【问题讨论】:

    标签: angularjs docker nginx nginx-location nginx-reverse-proxy


    【解决方案1】:

    尝试将以下内容添加到 nginx 配置中,以便将所有 /api/login 请求转发到 http://api:5000/

    location /api/login {
      proxy_pass http://api:5000;
    }
    

    您也可以使用rewrite 让 nginx 调用您的 API 服务器,而无需使用 /api/login 前缀。

    location /api/login {
      rewrite ^/api/login/(.*) /$1 break;
      proxy_pass http://api:5000;
    }
    

    CORS 标头可能不起作用,因为 nginx 正在返回它们,但您需要 API 服务器来返回它们。

    【讨论】:

    • @kichick,尝试了上述解决方案,但没有成功。我得到了这个错误,就像以前一样。 Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
    • 您是否也更新了 JavaScript 以访问端口 80 上的 /api/login?如果它的来源完全相同,它应该使用 CORS。
    • 我今天已经修好了。我从代理传递 nginx 配置中删除了端口(在这种情况下为 5000)。谢谢@kichik
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多