简体   繁体   English

docker-compose:无法连接到memcached容器

[英]docker-compose: Not able to connect to memcached container

I am learning docker. 我正在学习码头工人。 i want to add caching functionality in my application and hence using memcached. 我想在应用程序中添加缓存功能,并因此使用memcached。 below is my docker-compose.yml file 以下是我的docker-compose.yml文件

version: "3"
services:
 app:
   build: .
   volumes: 
    - .:/project 
   command: 'rails s -b 0.0.0.0 -p 3000' 
   container_name: 'test_rails'
   ports:
    - 3000:3000
   depends_on:
     - database
   links:
    - memcached  
 database:
  image: postgres:latest
  volumes:
    - ./data:/var/lib/postgresql/data
  environment:
    POSTGRES_USER: docker-user
    POSTGRES_PASSWORD: docker-password
    POSTGRES_DB: docker-db
 memcached:
  build:
   context: .
   dockerfile: Dockerfile.memcached
  command: 'tail -f /dev/null'

when i am trying to connect to memcached server which is inside memcached container from app container using below code 当我尝试使用以下代码从app容器连接到memcached容器内部的memcached服务器时

require 'dalli'
options = { :namespace => "app_v1", :compress => true }
dc = Dalli::Client.new('localhost:11211', options)

Then i am getting below error 然后我变得低于错误

WARN -- : localhost:11211 failed (count: 0) Errno::EADDRNOTAVAIL: Cannot assign requested address - connect(2) for "localhost" port 11211
Dalli::RingError: No server available
    from /usr/local/bundle/gems/dalli-2.7.10/lib/dalli/ring.rb:46:in `server_for_key'
    from /usr/local/bundle/gems/dalli-2.7.10/lib/dalli/client.rb:367:in `perform'
    from /usr/local/bundle/gems/dalli-2.7.10/lib/dalli/client.rb:130:in `set'
    from (irb):4
    from /usr/local/bin/irb:11:in `<main>'

can someone help me in understanding and resolving this issue. 有人可以帮助我理解和解决此问题。

Change : 变更:

dc = Dalli::Client.new('localhost:11211', options)

to : 至 :

dc = Dalli::Client.new('memcached:11211', options)

When you set up containers from compose they are all connected to the default network created by compose. 通过compose设置容器时,它们都已连接到compose创建的默认网络。 memcached is in this case the DNS name of memcached container and will be resolved to container IP automatically. 在这种情况下, memcachedmemcached容器的DNS名称,它将自动解析为容器IP。

You can not access one docker service from another service using localhost as each service has its own ip address and like small vm of its own. 您不能使用本地主机从另一个服务访问一个docker服务,因为每个服务都有自己的IP地址,就像自己的小型vm。 Use service name instead of localhost and docker will resolve it with ip addres of target service, 使用服务名称而不是localhost,而docker将使用目标服务的ip地址解析它,

`dc = Dalli::Client.new('memcached:11211', options)`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM