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)