1
votes

I have a dockerized back-end with golang gin server, postgresql and redis.

Everything starts correctly with this docker-compose.yaml file :

version: '3.9'
services:
  postgresql:
    image: 'postgres:13.1-alpine'
    volumes: 
      - data:/var/lib/postgresql/data
    env_file: 
      - ./env/postgre.env
    healthcheck:
        test: ["CMD-SHELL", "pg_isready -U postgres"]
        interval: 10s
        timeout: 5s
        retries: 5
    ports: 
      - '5432:5432'
  server:
    build: ./server
    ports:
      - '8000:8000'
    volumes: 
      - ./server:/app
    depends_on: 
      - postgresql
  redis:
    image: "redis"
    ports: 
      - "6379:6379"
    volumes: 
      - $PWD/redis-data:/var/lib/redis

volumes: 
  data:

Than I initialize redis in main func :

func main() {
    util.InitializeRedis()
    (...)

// InitializeRedis func

func newPool() *redis.Pool {
    return &redis.Pool{
        MaxIdle:3,
        IdleTimeout:240 * time.Second,
        DialContext: func(context.Context) (redis.Conn, error) {
            return redis.Dial("tcp",":6379")
        },
    }
}

var (
    pool *redis.Pool
)



func InitializeRedis() {
    flag.Parse()
    pool = newPool()
}

It doesn't prompt any error, but I cannot get connection with pool.Get in another function :

// Handle "/redis" for test

router.GET("/redis", util.ServeHome)

// ServeHome func

func ServeHome(ctx *gin.Context){

conn := pool.Get()
defer conn.Close()

var p1 struct{
    Title string `redis:"title" json:"title"`
    Author string `redis:"author" json:"author"`
    Body string `redis:"body" json:"body"`
}

p1.Title = "Example"
p1.Author = "Gary"
p1.Body = "Hello"

if _, err := conn.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
    log.Fatalf("Error occured with redis HMSEET, %v", err) // Error in console is from here
    return
}

(...)

And when I try to access /redis with Insomnia it shows: Error: Server returned nothing (no headers, no data) and in console logs : Error occured with redis HMSEET, dial tcp :6379: connect: connection refused

I couldn't find any article which solve this problem for me, so I do appreciate any help.

1

1 Answers

2
votes

Since you're using docker-compose Redis won't be available on :6379, instead it will be available on the hostname redis.

I think you'll need to update your code to the following:

redis.Dial("tcp","redis:6379")