如何让docker-compose容器看到Redis主机?

huangapple go评论62阅读模式
英文:

How to get docker-compose container to see Redis host?

问题

我有这个简单的docker-compose.yml文件:

version: '3.8'
services:
  bot:
    build:
      dockerfile: Dockerfile
      context: .
    links:
      - redis
    depends_on:
      - redis
  redis:
    image: redis:7.0.0-alpine
    ports:
     - "6379:6379"
    environment:
     - REDIS_REPLICATION_MODE=master
    restart: always
    volumes: 
      - cache:/data
    command: redis-server
volumes:
  cache:
    driver: local

这是bot(使用Go语言)连接到redis的方式:

import "github.com/go-redis/redis/v8"

func setRedisClient() {
  rdb = redis.NewClient(&redis.Options{
    Addr:     "redis:6379",
    Password: "",
    DB:       0,
  })
}

bot的Dockerfile:

FROM golang:1.18.3-alpine3.16
WORKDIR /go/src/bot-go
COPY . .
RUN go build .
RUN ./bot-go

但是当我运行docker-compose up --build时,我总是得到以下错误:

panic: dial tcp: lookup redis on 192.168.65.5:53: no such host

无论我对主机还是对docker-compose文件进行了什么更改,都无法找到redis主机。

当我将客户端配置为本地时,应用程序在没有Docker的情况下可以正常工作。

我到底做错了什么?

英文:

I have this simple docker-compose.yml file:

version: '3.8'
services:
  bot:
    build:
      dockerfile: Dockerfile
      context: .
    links:
      - redis
    depends_on:
      - redis
  redis:
    image: redis:7.0.0-alpine
    ports:
     - "6379:6379"
    environment:
     - REDIS_REPLICATION_MODE=master
    restart: always
    volumes: 
      - cache:/data
    command: redis-server
volumes:
  cache:
    driver: local

This is how the bot (in Go) connects to redis:

import "github.com/go-redis/redis/v8"

func setRedisClient() {
  rdb = redis.NewClient(&redis.Options{
    Addr:     "redis:6379",
    Password: "",
    DB:       0,
  })
}

bot Dockerfile:

FROM golang:1.18.3-alpine3.16
WORKDIR /go/src/bot-go
COPY . .
RUN go build .
RUN ./bot-go

But when I run docker-compose up --build I always get:

panic: dial tcp: lookup redis on 192.168.65.5:53: no such host

redis host is never seen no matter what changes I make to the host or to docker-compose file.

The app does work without Docker when I configure the client to local.

What I am doing wrong exactly?

答案1

得分: 3

问题是bot-go镜像一直在构建。在Dockerfile中将RUN ./bot-go改为CMD ["./bot-go"],一切都会正常工作。

英文:

The problem is the bot-go image never stops building. Change RUN ./bot-go to CMD [ "./bot-go" ] in the Dockerfile and everything will work fine.

huangapple
  • 本文由 发表于 2022年6月4日 23:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/72501074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定