Report this

What is the reason for this report?

MySQL connection timed out from Golang web app

Posted on September 25, 2024

Hello,

I have the MySQL database cluster set up, imported my database, set my droplet as a trusted source. I have also tried to set the password encryption to legacy for my database user. This is my Golang file that connects the DB:

package db

import (
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "log"
    "os"

    sql "github.com/go-sql-driver/mysql"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
)

func **ConnectDB**() (*gorm.DB, error) {

    rootCertPool := x509.**NewCertPool**()
    pem, err := os.**ReadFile**("crt/ca-certificate.crt")
    if err != nil {
        log.**Fatal**("Error reading CA Certificate for DB", err)
    }
    if ok := rootCertPool.**AppendCertsFromPEM**(pem); !ok {
        **panic**("Failed to append PEM.")
    }

    err = sql.**RegisterTLSConfig**("custom", &tls.Config{
        RootCAs:            rootCertPool,
        InsecureSkipVerify: true,
    })
    if err != nil {
        log.**Fatal**("Error registering TLS config: ", err)
    }

    DB_HOST := os.**Getenv**("DB_HOST")
    DB_USER := os.**Getenv**("DB_USER")
    DB_PASS := os.**Getenv**("DB_PASS")
    DB_NAME := os.**Getenv**("DB_NAME")
    connStr := fmt.**Sprintf**("%s:%s@tcp(%s)/?charset=utf8mb4&parseTime=True&loc=Local&tls=custom", DB_USER, DB_PASS, DB_HOST)
    db, err := gorm.**Open**(mysql.**Open**(connStr), &gorm.Config{})
    if err != nil {
        return nil, err
    }

    db.**Exec**(fmt.**Sprintf**("USE %s;", DB_NAME))

    return db, nil
}

I have also tried with the following connection string:

connStr := fmt.**Sprintf**("%s:%s@tcp(%s)/?charset=utf8mb4&parseTime=True&loc=Local&ssl-mode=REQUIRED", DB_USER, DB_PASS, DB_HOST)

I have set the following env variables on my droplet:

DB_USER=myusername
DB_PASS=mylegacypassword
DB_HOST=db-mysql-[my_db]-do-user-[id]-0.g.db.ondigitalocean.com:25060

I can connect to the database from my local machine, so the credentials must be correct. Searched through the docs and tried everything, but I couldn’t find a solution. As stated in the title, I get the following error:

2024-09-25 10:33:03] │ [error] failed to initialize database, got error dial tcp [ip]:25060: connect: connection timed out

Does anyone know why this is not working?

Thanks in advance!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Start building today

From GPU-powered inference and Kubernetes to managed databases and storage, get everything you need to build, scale, and deploy intelligent applications.