如何使用 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
上下文:
- 用 Rust 编写
Cargo.toml
:
[dependencies]
redis = "0.16.0"
hyper = "0.13"
本地发展 ✅
有用的东西:
- 运行 一个 redis docker 容器
bitnami/redis
,与 -p 6379:6379
一起发布
redis-cli
可以 成功连接到此 docker 容器
- 浏览器可以在
localhost:3000
处找到 rust 代码
GET /
显示一些文字 ✅
GET /redis
在redis中增加一个计数器,并显示它 ✅
运行 docker 中的 rust 代码 ❌
rustdocker容器连接redisdocker容器失败
- 运行同一个redis docker容器
bitnami/redis
,
- 浏览器可以在
localhost:3000
处命中 rust-container
GET /
显示一些文本,和以前一样 ✅
GET /redis
导致 rust 代码 panic ❌
Connection refused (os error 111)
我不确定这是否是我错误地处理“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 成功。
代码
https://github.com/thiskevinwang/rust-redis-docker/tree/for-Whosebug
上下文:
- 用 Rust 编写
Cargo.toml
:[dependencies] redis = "0.16.0" hyper = "0.13"
本地发展 ✅
有用的东西:
- 运行 一个 redis docker 容器
bitnami/redis
,与-p 6379:6379
一起发布
redis-cli
可以 成功连接到此 docker 容器- 浏览器可以在
localhost:3000
处找到 rust 代码GET /
显示一些文字 ✅GET /redis
在redis中增加一个计数器,并显示它 ✅
运行 docker 中的 rust 代码 ❌
rustdocker容器连接redisdocker容器失败
- 运行同一个redis docker容器
bitnami/redis
, - 浏览器可以在
localhost:3000
处命中 rust-containerGET /
显示一些文本,和以前一样 ✅GET /redis
导致 rust 代码 panic ❌Connection refused (os error 111)
我不确定这是否是我错误地处理“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 成功。