1

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:

Richard
  • 7,037
  • 2
  • 23
  • 76
  • `localhost` almost always means "the current container" in Docker. Since you're manually `docker run`ning the containers without Compose, they need to be on the same `docker run --network`; the "how to communicate" question linked above describes this setup. You'd then use the `docker run --name` of the Redis container as a host name. – David Maze Sep 30 '22 at 10:57
  • @DavidMaze Thank you for the explanation! I simply forgot that I need a Redis container running first before I can run my Go code. – Richard Oct 01 '22 at 10:38

1 Answers1

1

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

Slava Kuravsky
  • 2,702
  • 10
  • 16
  • Oh right. I need to use Docker Compose to up my Redis container first, then run this Dockerfile? – Richard Sep 30 '22 at 08:08
  • Yes, first start your redis (either with docker compose or like "docker run -d redis". You should consider proper networking (both containers should be in one network in order to communicate) and correct url of redis insead of localhost:6379. – Slava Kuravsky Sep 30 '22 at 08:14
  • It worked already. I used docker compose. I can't believe I missed such a silly thing. Thanks! – Richard Sep 30 '22 at 08:16