rails + docker + sidekiq +错误连接到127.0.0.1:6379上的Redis(Errno :: ECONNREFUSED)

Rah*_*jha 9 ruby-on-rails redis sidekiq docker docker-compose

运行带有docker和docker-compose的rails应用程序时出现此错误错误连接到127.0.0.1:6379上的Redis(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"]
Run Code Online (Sandbox Code Playgroud)

请找到我的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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

rox*_*azo 13

我使用docker-compose并添加.env文件

REDIS_URL=redis://redis:6379/0
Run Code Online (Sandbox Code Playgroud)

  • 根据sidekiq文档,sidekiq默认使用localhost:6379尝试连接到redis.但是,在开发中使用带有docker的localhost存在一些问题,这就是rails服务器绑定到0.0.0.0的原因.因此,我们需要使用env变量指定sidekiq可以连接到redis的特定地址 (3认同)

Nic*_*lay 5

不需要链接即可使服务进行通信-默认情况下,任何服务都可以使用该服务的名称访问任何其他服务。

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

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