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
Change :
to :
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 ofmemcached
container and will be resolved to container IP automatically.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,