How to connect django to redis docker container?

I am trying to connect django to a container of a redix container

Here is my docker file

FROM ubuntu:14.04 RUN apt-get update && apt-get install -y redis-server EXPOSE 6379 ENTRYPOINT ["/usr/bin/redis-server"] 

Here is the result of docker ps -a

 4f7eaeb2761b /redis "/usr/bin/redis-serve" 16 hours ago Up 16 hours 6379/tcp redis 

Here's a quick health check that redis works inside a docker container

  docker exec -ti redis bash root@4f7eaeb2761b :/# redis-cli ping PONG root@4f7eaeb2761b :/# redis-cli 127.0.0.1:6379> exit 

Here is my Django settings.py

 CACHES = { 'default': { 'BACKEND': 'redis_cache.RedisCache', 'LOCATION': 'localhost:6379', }, } 

Here is my look

 from django.shortcuts import render from django.template import loader from django.http import HttpResponse from django.views.decorators.cache import cache_page @cache_page(60 * 15) def index(request): template = loader.get_template('./index.html') return HttpResponse(template.render()) 

Below is an alternative access to redis

 import redis def index(request): r = redis.StrictRedis(host='localhost', port=6379, db=0) print r # this line doesn't cause error r.set('foo', 'bar') # this line cause error template = loader.get_template('./index.html') return HttpResponse(template.render()) 

I checked that everything works without the @cache_page decorator

When I used the decorator, I get

 Error 61 connecting to localhost:6379. Connection refused. 

I'm not sure how I can open the docker container by setting the Expose port, any help would be appreciated

thanks

+5
source share
1 answer

What you need to understand is that ports are open in the container! = Open systems.

The Docker container for redis pushes port 6379 from the container - this is not the same port on the host system.

Assuming you are launching docker with:

 docker run -ti redis bash 

By default, Docker will select a random port on the host to bind to the port that exposes the container. You can check host ports using the command (it won’t show anything if the port is not open):

 docker port CONTAINER_ID 

Instead, you want to run it as follows:

 docker run -ti redis bash -p 6379:6379 

This tells Docker to bind host port 6379 to container port 6379. Then the docker port will show you something like this:

 $ docker port CONTAINER_ID 6379/tcp -> 0.0.0.0:6379 

You can also use the docker-compose.yml to configure it.

More details:

+2
source

Source: https://habr.com/ru/post/1245397/


All Articles