enable CORS in docker for rails apps rest-client
I have two applications running in separate docker images. First is exposed on ports 3000:3000 and second 4000:4000. First application has some resources which I wanna get by second application using rest-client.
Probably it’s a problem with docker containers.
Here are errors:
Errno::ECONNREFUSED in FilmsController#index
Failed to open TCP connection to localhost:3000 (Connection refused – connect(2) for “localhost” port 3000)
- exposes resources on http://localhost:3000/movies
- is open for other networks
- allows cross origin request
application.rb file for first application
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
- runs on port:4000
- has one model Film
- one controller
class Film require 'rest-client' def self.all RestClient.get 'localhost:3000/movies.json' end end
class FilmsController < ApplicationController def index render json: Film.all end end
Everything was working fine since it was one application. The problem appears when I split into two docker containers. I guess that one container blocks request from another, but couldn’t find solution. Any help would be very appreciated.
One Solution collect form web for “enable CORS in docker for rails apps rest-client”
Each docker container runs in a separate networking namespace by default, which includes getting its own private loopback interface (aka localhost) that is separate from every other container and the host. To connect between two containers, they need to be on the same docker network, and then as long as that network is not the default network named “bridge” (the name, not the network driver), you can connect between containers using their container name. Note that you do not need to publish or expose the port for container to container networking, that former is only needed for allowing external access to the container.
So if you are using
docker run (otherwise you should include your docker-compose.yml), you would have:
docker network create railsnet docker run --net railsnet --name=app1 ... docker run --net railsnet --name=app2 ...
And then if app1 listened on port 3000 inside the container, you could connect from app2 to app1:3000/xyz.