node.js - 为什么容器 IP 和别名之间的交换会导致 AJAX 请求出现差异?

标签 node.js nginx docker

我有一个小示例项目located here that illustrates the problem I am seeing使用 nginx + node + host docker 堆栈时。

我有 2 个容器:

  • 一个仅返回 json 对象的 node(express)应用程序。它是基于 this website 启用的 COR 。它的端口通过 3000:80
  • 发布到主机
  • nginx 服务器,也基于 this website 启用 COR 。它仅从默认位置 (/usr/shared/nginx/html) 提供静态内容(index.htmlmain.js 文件)。其端口通过 8080:80 发布。

当从主机单独运行容器时,我可以访问 Node 服务器并查看返回的 JSON 对象。当我访问 nginx 服务器时,我看到 index.htmlmain.js 中的 javascript 代码运行。

现在我已将 Node 应用程序容器链接到 nginx 服务器容器。从 nginx 容器的 main.js 文件中,我尝试访问 http://nodeapp/api 处的服务器。我看到 COR 错误

XMLHttpRequest cannot load http://nodeapp/api. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

奇怪的是,响应 header 表明它来自 nginx,并且不是我所期望的 Express 应用程序。 nginx 容器也没有记录任何内容。

有效的事情

  • 如果我将 XMLHttpRequest 的 url 更改为 Node 容器的 IP(例如 172.17.0.2),它会按预期工作并且响应 header 表明它来自 Express 服务器。在我的 /etc/hosts 文件中有一个条目:
    172.17.0.2 nodeapp abc123ContainerId fastserve_nodeapp_run_1

  • 当我从交互式 tty 容器中 curl Node 容器时,它也按预期工作。

  • 如果我加载 Node 容器并使用 http-server (主机上的服务器),它会按预期工作并且响应 header 表明它来自 Express 服务器。

最佳答案

以防万一它有影响,old thread (2013)提到了 docker 守护进程上的 cor 选项。
如今(2015 年第 4 季度),docker daemon包括:

--api-cors-header=""                   Set CORS headers in the remote API

To set cross origin requests to the remote api please give values to --api-cors-header when running Docker in daemon mode. Set * (asterisk) allows all, default or blank means CORS disabled

$ docker -d -H="192.168.1.9:2375" --api-cors-header="http://foo.bar"

这可能是您的情况下使用的设置。

关于node.js - 为什么容器 IP 和别名之间的交换会导致 AJAX 请求出现差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193249/

相关文章:

node.js jade - 无法访问嵌套数组元素

javascript - 如何拆分单体 node.js javascript

node.js - Docker 化 Node.js 应用程序时的 EADDRNOTAVAIL

docker - minikube 0.30.0 DNS在带有Docker 18.06.1-ce和vm-driver = none的CentOS 7上不起作用

node.js - 为什么当我安装新的 npm 包时,我必须运行 "docker-compose down",然后运行 ​​ "docker-compose up --build"?

ruby-on-rails - 如何配置 nginx 以在域中安装 Rails 应用程序并在/blog/中安装 WordPress?

python - uwsgi + nginx + flask : upstream prematurely closed

http - 重写重定向以包括用于访问服务的端口

linux - 如何使用 NetCat for Windows 将二进制文件发送到 TCP 连接?

Dockerfile 无法复制文件。 ("cp"命令)