Error 99 connecting to localhost:6379. Cannot assign requested address Error 99 connecting to localhost:6379. Cannot assign requested address flask flask

Error 99 connecting to localhost:6379. Cannot assign requested address


In the flask app I have a function that tries to create a redis client

db = redis.Redis(host='localhost', port=6379, decode_responses=True)

When your flask process runs in a container, localhost refers to the network interface of the container itself. It does not resolve to the network interface of your docker host.

So you need to replace localhost with the IP address of the container running redis.

In the context of a docker-compose.yml file, this is easy as docker-compose will make service names resolve to the correct container IP address:

version: "3"services:  my_flask_service:    image: ...  my_redis_service:    image: ...

then in your flask app, use:

db = redis.Redis(host='my_redis_service', port=6379, decode_responses=True)


I had this same problem, except the service I wanted my container to access was remote and mapped via ssh tunnel to my Docker host. In other words, there was no docker-compose service for my code to find. I solved the problem by explicitly telling redis to look for my local host as a string:

pyredis.Redis(host='docker.for.mac.localhost', port=6379)


Anyone using only docker to run a container,you can add --network=host in the command like docker run --network=host to make docker use the network of the host while running the container.

You can also use a host network for a swarm service, by passing --network host to the docker service create command.
Make sure you don't publish any port while doing this. like -p 80:8000

I am not sure if Docker compose supports this.

N.b. this is only supported in linux.