且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

docker-compose + django + redis - 连接到 127.0.0.1:6379 时出现错误 111.拒绝连接

更新时间:2022-11-16 22:59:36

127.0.0.1 在 Docker 中几乎总是意味着这个容器".如果您在 Docker Compose 下运行您的应用程序,它

127.0.0.1 in Docker almost always means "this container". If you're running your application under Docker Compose, it

... 为您的应用设置单个网络.服务的每个容器都加入默认网络,并且该网络上的其他容器可达,并且可发现在与容器名称相同的主机名上.

... sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

也就是说,在这个 docker-compose.yml 文件的上下文中,有主机名 redisweb 指向两个容器.

That is, within the context of this docker-compose.yml file, there are host names redis and web that point at the two containers.

您已经完成了一项重要的配置工作.当你的代码说

You've already done one of the important configuration things. When your code says

REDIS_HOST = os.environ.get('REDIS_HOST', '127.0.0.1')

您可以设置一个覆盖内置默认值的环境变量.所以在这里你只需要在你的 docker-compose.yml 文件中添加一个环境变量设置:

you can set an environment variable that overrides the built-in default value. So here you just need to add an environment variable setting to your docker-compose.yml file:

version: '3'
services:
  redis:
    image: "redis:alpine"
  web:
    build: . # current directory
    environment:
      - REDIS_HOST=redis
    ports:
      - "8000:8000"
    # application source code and default command are built into the image