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

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

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

问题

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

FROM golang:alpine as builder

LABEL maintainer="..."

RUN apk update && apk add --no-cache git

WORKDIR /app

COPY go.mod go.sum ./

RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder /app/main .

EXPOSE 6379

CMD ["./main"]

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

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

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

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

	if err := s.Client.Ping().Err(); err != nil {
		log.Fatalf("Failed to create a Redis client: %s", err)
	}

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

我阅读过的一些问题:

英文:

I tried running a Redis container with the following Dockerfile.

FROM golang:alpine as builder

LABEL maintainer="..."

RUN apk update && apk add --no-cache git

WORKDIR /app

COPY go.mod go.sum ./

RUN go mod download

COPY . .

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

FROM alpine:latest
RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder /app/main .

EXPOSE 6379

CMD ["./main"]

Then, I ran

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

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

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

	if err := s.Client.Ping().Err(); err != nil {
		log.Fatalf("Failed to create a Redis client: %s", err)
	}

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:

确定