go - 通过docker连接golang和redis

标签 go redis docker docker-compose

我正在尝试使用 docker-compose 通过 Docker 连接 golang 和 reds,但我不太走运。我已经在 https://github.com/davidwilde/docker-compose-golang-redis/tree/stackoverflow_question 发表了我的尝试并在下面列出了日志。

Redis 说它已准备好接受连接,但我的 golang 应用程序使用 gopkg.in/redis.v3说不。

 ~/workspace/composetest   master ●  docker-compose up
Starting composetest_db_1...
Starting composetest_web_1...
.
.
.
ur kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled.
db_1  | 1:M 20 Nov 05:58:33.371 * DB loaded from disk: 0.000 seconds
db_1  | 1:M 20 Nov 05:58:33.371 * The server is now ready to accept connections on port 6379
web_1 | panic: dial tcp [::1]:6379: getsockopt: connection refused
web_1 |
web_1 | goroutine 1 [running]:
web_1 | main.main()
web_1 |     /go/src/app/app.go:19 +0x131
web_1 |
web_1 | goroutine 17 [syscall, locked to thread]:
web_1 | runtime.goexit()
web_1 |     /usr/local/go/src/runtime/asm_amd64.s:1696 +0x1
web_1 | panic: dial tcp [::1]:6379: getsockopt: connection refused
web_1 |
web_1 | goroutine 1 [running]:
web_1 | main.main()
web_1 |     /go/src/app/app.go:19 +0x131
web_1 |
web_1 | goroutine 17 [syscall, locked to thread]:
web_1 | runtime.goexit()
web_1 |     /usr/local/go/src/runtime/asm_amd64.s:1696 +0x1

最佳答案

所以我们有两个不同的容器,在这种情况下意味着两个不同的“本地主机”。

client := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
    Password: "",
    DB: 0,
})

因此,您的应用正在向其自己的沙盒容器发出请求,而不是向包含 Redis 的“其他”沙盒容器发出请求。

你有两个选择;

在您的撰写文件中提供一个映射,例如 redisdb:db 并传递该信息而不是本地主机。

或者,使用“--net=host”选项以便在不更改代码的情况下为您的容器提供通用网络。

编辑:打字错误

关于go - 通过docker连接golang和redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33820025/

相关文章:

ubuntu - 无法在 Ubuntu 14.04 上找到包 docker-ce

go - 如果使用 postgres 连接的 SQLX transaction.Commit 失败,是否需要调用 transaction.RollBack

node.js - 使用 NPM `redis` 包,.exists(...) 始终返回 true。为什么?

optimization - 当字符串超过 7 个字节时,字符串的 Redis int 表示更大,否则更小

python - Redis py : when to use connection pool?

docker - 如何在不更改公共(public) DNS 地址的情况下使用 ECR 中的最新 docker 镜像更新 ECS 服务?

docker - 没有足够的熵来支持在 boot2docker 中运行的 docker 容器中的/dev/random

go - 如何将接口(interface)内的值转换为golang中的 map ?

go - 为什么 Go slice 不只是在重新分配时切换底层数组?

map - Go:什么决定了映射键的迭代顺序?