Error dial tcp 127.0.0.1:6379: connect: connection refused when starting Redis container without Docker Compose

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

Error dial tcp 127.0.0.1:6379: connect: connection refused when starting Redis container without Docker Compose

问题

我尝试使用以下Dockerfile运行一个Redis容器。

  1. FROM golang:alpine as builder
  2. LABEL maintainer="..."
  3. RUN apk update && apk add --no-cache git
  4. WORKDIR /app
  5. COPY go.mod go.sum ./
  6. RUN go mod download
  7. COPY . .
  8. RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
  9. FROM alpine:latest
  10. RUN apk --no-cache add ca-certificates
  11. WORKDIR /root/
  12. COPY --from=builder /app/main .
  13. EXPOSE 6379
  14. CMD ["./main"]

然后,我运行了以下命令:

  1. docker build -t redis .
  2. docker run -dp 6379:6379 redis

之后,在代码的这一部分出现了错误:

  1. s.Client = redis.NewClient(&redis.Options{
  2. Addr: "localhost:6379",
  3. Password: "",
  4. DB: 0,
  5. })
  6. if err := s.Client.Ping().Err(); err != nil {
  7. log.Fatalf("Failed to create a Redis client: %s", err)
  8. }

我在Stackoverflow上阅读了一些类似的问题,并尝试将地址更改为redis:6379,但没有成功。有人可以帮我解释为什么会出现连接被拒绝的错误吗?

我阅读过的一些问题:

英文:

I tried running a Redis container with the following Dockerfile.

  1. FROM golang:alpine as builder
  2. LABEL maintainer="..."
  3. RUN apk update && apk add --no-cache git
  4. WORKDIR /app
  5. COPY go.mod go.sum ./
  6. RUN go mod download
  7. COPY . .
  8. RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
  9. FROM alpine:latest
  10. RUN apk --no-cache add ca-certificates
  11. WORKDIR /root/
  12. COPY --from=builder /app/main .
  13. EXPOSE 6379
  14. CMD ["./main"]

Then, I ran

  1. docker build -t redis .
  2. docker run -dp 6379:6379 redis

Afterwards, there is an error on this side of the code:

  1. s.Client = redis.NewClient(&redis.Options{
  2. Addr: "localhost:6379",
  3. Password: "",
  4. DB: 0,
  5. })
  6. if err := s.Client.Ping().Err(); err != nil {
  7. log.Fatalf("Failed to create a Redis client: %s", err)
  8. }

I have read some similar questions in Stackoverflow and tried changing the address to redis:6379, but it didn't work. Could someone help me explain why there is this connection refused error?

Some questions I've read:

答案1

得分: 1

你的镜像是基于alpine的,而不是redis镜像。我看不到你在Dockerfile中安装redis的地方。

英文:

You image is based on alpine, not on redis image. And I can't see where do you install redis in your Dockerfile.

huangapple
  • 本文由 发表于 2022年9月30日 15:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73905656.html
匿名

发表评论

匿名网友

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

确定