Docker-compose - Redis at 0.0.0.0 instead of 127.0.0.1

为君一笑 提交于 2020-02-02 03:19:28

问题


I havs migrated my Rails app (local dev machine) to Docker-Compose. All is working except the Worker Rails instance (batch) cannot connect to Redis.

Completed 500 Internal Server Error in 40ms (ActiveRecord: 2.3ms)

Redis::CannotConnectError (Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)):

In my docker-compose.yml

redis:
  image: redis
  ports:
    - "6379:6379"

batch:
  build: .
  command: bundle exec rake environment resque:work QUEUE=*
  volumes:
    - .:/app
  links:
    - db
    - redis
  environment:
    - REDIS_URL=redis://redis:6379

I think the Redis instance is available via the IP of the Docker host.

$ docker-machine ls
NAME      ACTIVE   DRIVER       STATE     URL                       SWARM   DOCKER    ERRORS
default   *        virtualbox   Running   tcp://192.168.99.100:2376           v1.10.0

Accessing via 0.0.0.0 doesn't work

$ curl 0.0.0.0:6379 
curl: (7) Failed to connect to 0.0.0.0 port 6379: Connection refused

Accessing via the docker-machine IP I think works:

$ curl http://192.168.99.100:6379
-ERR wrong number of arguments for 'get' command
-ERR unknown command 'Host:'

EDIT

After installing redis-cli in the batch instance, I was able to hit the redis server using the 'redis' hostname. I think the problem is possibly in the Rails configuration itself.


回答1:


If you run

docker-compose run --rm batch env | grep REDIS

you will get the env variables that your container has (the link line in the compose will auto-generate some). Then all you need to do is look for one along the lines of _REDIS_1_PORT... and use the correct one. I have never had luck connecting my rails to another service in any other way. But luckily these env variables are always generated on start so they will be up to date even if the container IP happens to change between startups.




回答2:


You should use the hostname redis to connect to the service, although you may need to wait for redis to start.




回答3:


Facepalm!!!

The docker containers were communicating just fine, the problem was I hadn't told Resque (the app using Redis) where to find it. Thank you to "The Real Bill" for pointing out I should be using docker-cli.

For anyone else using Docker and Resque, you need this in your config/initializers/resque.rb file:

Resque.redis = Redis.new(host: 'redis', port: 6379)
Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection }


来源:https://stackoverflow.com/questions/35350679/docker-compose-redis-at-0-0-0-0-instead-of-127-0-0-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!