通过Docker连接Golang和Redis

5
我正在尝试使用docker-compose将golang和redis连接起来,但是运气不太好。我已经在https://github.com/davidwilde/docker-compose-golang-redis/tree/stackoverflow_question上发布了我的尝试,并列出了以下日志。
Redis表示已准备好接受连接,但我使用gopkg.in/redis.v3的golang应用程序却没有成功。
 ~/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

在调用源代码之前,请使用Telnet或NC检查连通性。 - Jiang YD
2个回答

8

因此,我们有两个不同的容器,这意味着在这种情况下有两个不同的“localhost”。

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

因此,你的应用程序正在向其自己的沙箱容器发出请求,而不是向包括redis的“其他”沙箱容器发出请求。

你有两个选择:

在compose文件中提供映射,如redisdb:db,并传递该信息,而不是使用localhost。

或者,使用“--net = host”选项为你的容器提供共享网络,而不更改你的代码。

编辑:笔误


3
非常感谢。我只是将app.go更改为Addr:"db:6379"。 - Mr Wilde
3
在GitHub上的这个链接是一个正在工作的版本,它包含了使用Docker Compose配置Golang和Redis的代码。 - Mr Wilde

0

@Gladmir的回答非常好。只是为了扩展他/她的答案,我不需要从我的Golang代码中删除localhost

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

我修改了我的Docker Compose文件,使用了network_mode: "host"

version: "3.9"
services:
  web:
    build:
      context: .
    network_mode: "host"
  redis:
    container_name: "redis"
    image: "redis:alpine"
    command: redis-server /usr/local/etc/redis/redis.conf
    ports:
      - "6379:6379"
    volumes:
      - $PWD/configs/redis.conf:/usr/local/etc/redis/redis.conf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接