2

I'm currently trying to introduce docker compose to my project. It includes a golang backend using the redis in-memory database.

version: "3.9"
services:
  frontend:
    ...
  backend:
    build:
      context: ./backend
    ports:
      - "8080:8080"
    environment:
      - NODE_ENV=production
    env_file:
      - ./backend/.env
  redis:
    image: "redis"
    ports:
      - "6379:6379"
FROM golang:1.16-alpine
RUN mkdir -p /usr/src/app
ENV PORT 8080
WORKDIR /usr/src/app
COPY go.mod /usr/src/app
COPY . /usr/src/app
RUN go build -o main .
EXPOSE 8080
CMD [ "./main" ]

The build runs successfully, but after starting the services, the go backend immediately exits throwing following error:

Error trying to ping redis: dial tcp 127.0.0.1:6379: connect: connection refused

Error being catched here:

_, err = client.Ping(ctx).Result()
if err != nil {
    log.Fatalf("Error trying to ping redis: %v", err)
}

How come the backend docker service isn't able to connect to redis? Important note: when the redis service is running and I start my backend manually using go run *.go, there's no error and the backend starts successfully.

Johnny Kontrolletti
  • 727
  • 1
  • 10
  • 22

3 Answers3

7

When you run your Go application inside a docker container, the localhost IP 127.0.0.1 is referring to this container. You should use the hostname of your Redis container to connect from your Go container, so your connection string would be:

redis://redis
Jeroen
  • 1,991
  • 2
  • 16
  • 32
4

I found I was having this same issue. Simply changing (in redis.NewClient(&redis.Options{...}) Addr: "localhost:6379"to Addr: "redis:6379" worked.

sheddo
  • 41
  • 1
0

Faced similar issue with Golang and redis.

version: '3.0'
services:
  redisdb:
    image: redis:6.0
    restart: always
    ports:
      - "6379:6379"
    container_name: redisdb-container
    command: ["redis-server", "--bind", "redisdb", "--port", "6379"]

  urlshortnerservice:
    depends_on:
      - redisdb
    ports:
      - "7777:7777"
    restart: always
    container_name: url-shortner-container
    image: url-shortner-service

In redis configuration use

redisClient := redis.NewClient(&redis.Options{
        Addr:     "redisdb:6379",
        Password: "",
        DB:       0,
    })
infiniteLearner
  • 3,555
  • 2
  • 23
  • 32