Rails + Docker + Sidekiq + 连接 Redis 失败:127.0.0.1:6379 (Errno::ECONNREFUSED)

12
在使用Docker和docker-compose运行我的Rails应用时,我遇到了以下错误: Error connecting to Redis on 127.0.0.1:6379 (Errno::ECONNREFUSED)
请查看我的Docker文件。
# Copy the Gemfile as well as the Gemfile.lock and install
# the RubyGems. This is a separate step so the dependencies
# will be cached unless changes to one of those two files
# are made.
COPY Gemfile Gemfile.lock ./
RUN gem install bundler && bundle install --jobs 20 --retry 5

# Copy the main application.
COPY . ./app

# Expose port 3000 to the Docker host, so we can access it
# from the outside.
EXPOSE 3000

# The main command to run when the container starts. Also
# tell the Rails dev server to bind to all interfaces by
# default.
CMD ["bundle", "exec", "rails", "server", "-b", "0.0.0.0"]
请找到我的docker-compose.yml文件。
version: "2"
services:
  redis:
    image: redis
    command: redis-server
    ports:
      - "6379:6379"
  postgres:
    image: postgres:9.4
    ports:
      - "5432"

  app:
    build: .
    command: rails server -p 3000 -b '0.0.0.0'
    volumes:
      - .:/app
    ports:
      - "3000:3000"
    links:
      - postgres
      - redis
      - sidekiq

  sidekiq:
    build: .
    command: bundle exec sidekiq
    depends_on:
      - redis
    volumes:
      - .:/app
    env_file:
      - .env

提前致谢!

2个回答

27

我使用docker-compose并在.env文件中添加了内容。

REDIS_URL=redis://redis:6379/0

这对我来说是有效的,但有人能解释一下为什么吗?我想要能够理解它为什么有效。我大致明白 - 它将其指向了正确的路径/URL,但为什么我们必须将其放在.env文件中呢? - lscott3
1
好问题。我只是通过谷歌搜索找到了这个,但我不知道为什么 :( - roxdurazo
4
根据Sidekiq文档,Sidekiq默认使用localhost:6379连接到Redis。但是,在开发时使用Docker时会遇到一些问题,这就是为什么Rails服务器绑定到0.0.0.0的原因。因此,我们需要通过环境变量指定Sidekiq可以连接到Redis的特定地址。 - Nathan Lauer

8

链接不是必需的,以使服务之间通信 - 默认情况下,任何服务都可以通过该服务的名称到达任何其他服务。

根据您的docker-compose.yaml文件,您只能从主机访问127.0.0.1:6379上的redis容器。

容器在其网络中相互通信,因此您可以从rails应用程序容器访问redis:6379上的redis容器。


这并没有回答问题,只是解释了为什么会发生这种情况。有没有办法使用容器化的Redis实例,但仍然将其提供在127.0.0.1上?我猜没有吧? - ortonomy
1
要在127.0.0.1上提供服务,您应该在docker-compose文件中公开sidekiq容器端口6379,这样您就可以引用本地主机,但要小心,因为公开所有容器的重要端口并不总是一个好主意。 - Rafael Baldasso Audibert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接