skip to Main Content

I am learning docker. i want to add caching functionality in my application and hence using memcached. below is my docker-compose.yml file

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

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.

2

Answers


  1. 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. memcached is in this case the DNS name of memcached container and will be resolved to container IP automatically.

    Login or Signup to reply.
  2. 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. Use service name instead of localhost and docker will resolve it with ip addres of target service,

    `dc = Dalli::Client.new('memcached:11211', options)`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search