如何使用 redis-rs 从 Docker 容器内部连接到 Redis?

How to connect to Redis from inside Docker container using redis-rs?

代码

https://github.com/thiskevinwang/rust-redis-docker/tree/for-Whosebug

上下文:

本地发展 ✅

有用的东西:

运行 docker 中的 rust 代码 ❌

rustdocker容器连接redisdocker容器失败


我不确定这是否是我错误地处理“docker 网络”的问题,或者我是否错误地使用了 redis crate(尽管文档非常稀疏)。

你在 docker-compose.yaml 中有这个:

services:
  hyper:
    build: .
    ports:
      - "3000:3000"
    expose:
      - "3000"
    links:
      - redis # links this container to "redis" container
  redis:
    image: "bitnami/redis:latest"
    ports:
      - "6379:6379"
    expose:
      - "6379"

From the Docker Compose docs on links:

Containers for the linked service are reachable at a hostname identical to the alias, or the service name if no alias was specified.

因此错误出现在 main.rs 中的第 70 行:

let client = redis::Client::open("redis://127.0.0.1:6379")?;

这是行不通的,因为 redis 实例 运行 与您的 Rust 代码不在同一个容器中。您必须通过 docker 撰写文件中建立的 link 连接到它,在本例中为:

let client = redis::Client::open("redis://redis:6379")?;

完成此修复后,获取 GET localhost:3000/redis returns 成功。