在 docker 中为 rails 个应用程序 rest-client 启用 CORS

enable CORS in docker for rails apps rest-client

我在单独的 docker 图像中有两个应用程序 运行。第一个暴露在端口 3000:3000 和第二个 4000:4000 上。第一个应用程序有一些资源,我想通过第二个应用程序使用 rest-client 获得这些资源。

可能是 docker 个容器的问题。

以下是错误:

//第一个应用程序:

application.rb 首次申请文件

module Movies
   class Application < Rails::Application
      config.web_console.whiny_requests = false

      config.middleware.insert_before 0, Rack::Cors do
        allow do
          origins '*'
          resource '*', :headers => :any, :methods => [:get, :post, 
          :options]
       end
     end
  end
end

//第二次申请:

胶片型号:

class Film
  require 'rest-client'
    def self.all
      RestClient.get 'localhost:3000/movies.json'
  end
end

films_controller:

class FilmsController < ApplicationController
  def index
    render json: Film.all
  end
end

一切正常,因为它是一个应用程序。当我分成 两个 docker 个容器时出现问题 。我猜想 一个容器阻止了另一个容器的请求,但找不到解决方案。任何帮助将不胜感激。

默认情况下,每个 docker 容器都在单独的网络命名空间中运行,其中包括获得自己的专用环回接口(也称为本地主机),该接口与其他所有容器和主机分开。两个容器之间连接,需要在同一个docker网络上,然后只要那个网络不是默认的名为"bridge"的网络(名字,不是网络驱动),就可以使用容器名称在容器之间进行连接。请注意,您不需要将容器的端口发布或公开到容器网络,前者只需要允许外部访问容器。

因此,如果您使用 docker run(否则您应该包括 docker-compose.yml),您将拥有:

docker network create railsnet
docker run --net railsnet --name=app1 ...
docker run --net railsnet --name=app2 ...

然后如果 app1 在容器内的端口 3000 上侦听,您可以从 app2 连接到 app1:3000/xyz。