Go application in docker container on EC2 instance can't reach ElastiCache nor RDS

39 Views Asked by At

I am new to AWS so please bare with me as I know variations of this question have been asked but I still could not find a solution.

I have the below:

  • Amazon linux EC2 instance
  • ElastiCache instance
  • Amazon RDS instance.

All of them belong the same security group

enter image description here

enter image description here

  • from EC2 I connect connect to my DB on RDS using a psql client, and I can reach ElastiCache instance through telnet
  • on my EC2 instance I have a Go application running in a docker container with --network=host flag set when starting the docker
  • the Go application is not able to reach my DB not redis I get the below errors:

when connection to psql:

could not query DB: pq: no pg_hba.conf entry for host \"172.a.b.c\", user \"postgres,\", database \"postgres\", no encryption"

note that EC2 instance IP is also 172.a.b.c so we know --network=host flag actually "took"

when creating redis client:

"Error creating redis client: read tcp 172.a.b.c:53404->172.x.y.z:6379: i/o timeout"

this is how I am running my container for the time being:

 docker run    -v "$(pwd)/config.toml":/data/conf/config.toml   --name test   --network=host   image_name

Extras:

this the code to open DB connection and test it:

    DBstring := fmt.Sprintf("host =%v port=%d database=%s sslmode=%s user=%v", conf.Database.IP, conf.Database.Port, conf.Database.Name, conf.Database.SSLMode, conf.Database.Username)
    if conf.Database.Password != "" {
        DBstring = fmt.Sprintf("%s, password=%s", DBstring, conf.Database.Password)
    }
    log.Info(fmt.Sprintf("database string %s", DBstring))
    Connection, err = sql.Open("postgres", DBstring)
    if err != nil {
        log.Error(fmt.Sprintf("could not connect to DB: %s", err.Error()))
    }
    // test DB connection
    _, er := Connection.Exec("select 1")
    if er != nil {
        log.Error(fmt.Sprintf("could not query DB: %s", er.Error()))
    }

this is the code to create redis client:

    redisAddress := fmt.Sprintf("%s:%d", conf.Redis.IP, conf.Redis.Port)
    log.Info(redisAddress)
    redisClient = redis.NewClient(&redis.Options{
        Addr:     redisAddress,        // Your Redis server address
        Password: conf.Redis.Password, // No password
        DB:       conf.Redis.DB,       // Default DB
    })

    err = redisClient.Ping(context.TODO()).Err()
    if err != nil {
        log.Error(fmt.Sprintf("Error creating redis client: %s", err.Error()))
    }
0

There are 0 best solutions below