skip to Main Content

I have a memcached service running on port 11211 in a docker container and I want to access this service from within another container using 127.0.0.1:11211. Im using docker-compose and nothing of “links”, “ports” or “expose” seems to work for me. I don’t wanna have to access with the ip of the memcached docker container instead I want to access it as it were a local service of the other container. Is there any solution?

Thanks!

version: '2'
services:
  memcached:
    build: ./memcached
    image: memcached_img
    expose:
      - "11211"
  web:
    build: .
    image: app:latest
    mem_limit: 512m
    ports:
      - "3000:3000"
    command: [ "script/startup.sh", "web" ]
  worker:
    build: .
    image: app:latest
    mem_limit: 512m
    command: [ "script/startup.sh", "worker" ]

4

Answers


  1. You can whether use ‘expose XXXX’ in Dockerfile, or use -p when running the container for the 1st time.
    It will be super helpful for us to help you if you provide your Dockerfile that built your image from.

    Login or Signup to reply.
  2. First, you need to change Memcache conf to allow to connect with other hosts

     go to /etc/memcached.conf:
     change -l 127.0.0.1 to -l 0.0.0.0 # or simply comment it out
    

    build image.

    in your docker-compose file

    services:
      memcache:
        ports:
          - host_port: docker_service_port
    
    Login or Signup to reply.
  3. localhost inside the container is a different isolated network. Not the host’s localhost.

    You could add depends_on: memcached to the web container. This will add the memcached host to the web container and you will be able to ping that host from there. Docker will take care of port forwarding. It will also make sure to start web only once memcached has already started. You could then telnet memcached 11211 from within web.

    Login or Signup to reply.
  4. Create docker network to communicate between containers

    version: '2'
    services:
      memcached:
        build: ./memcached
        image: memcached_img
        expose:
          - "11211"
        networks:
          - web-network
      web:
        build: .
        image: app:latest
        mem_limit: 512m
        ports:
          - "3000:3000"
        command: [ "script/startup.sh", "web" ]
        networks:
          - web-network
      worker:
        build: .
        image: app:latest
        mem_limit: 512m
        command: [ "script/startup.sh", "worker" ]
    networks:
       web-network:
          driver: bridge
    

    Now you can “access” services using their names. E.g. you can access memcached service from web service using memcached:11211 as host:port

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search