You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab Runner环境下Go应用无法连接MySQL的问题求助

Fixing MySQL Connection Refused in GitLab CI for Your Go App

It looks like you're hitting a common pitfall with GitLab CI services—let's break down what's going wrong and how to fix it:

1. You're using the wrong job image

Your job is set to use image: mysql, but that's a container for running MySQL itself. To run your Go app, you need a Go-based image instead. Swap that out for something like:

image: golang:1.21 # Use the Go version your app requires

2. Your Go app is trying to connect to localhost (127.0.0.1)

In GitLab CI, the MySQL service runs in a separate container from your job. That means 127.0.0.1 in your job container doesn't point to the MySQL service. Instead, you can reach it using the service name (mysql) as the hostname.

Update your Go code to use the MYSQL_HOST environment variable you've already defined:

package main

import (
    "database/sql"
    "fmt"
    "os"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // Pull connection details from environment variables
    host := os.Getenv("MYSQL_HOST")
    user := os.Getenv("MYSQL_USER")
    password := os.Getenv("MYSQL_ROOT_PASSWORD")
    dbName := os.Getenv("MYSQL_DATABASE")

    // Build the connection string using the service hostname
    connStr := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s", user, password, host, dbName)
    
    db, err := sql.Open("mysql", connStr)
    if err != nil {
        panic(fmt.Errorf("failed to connect: %v", err))
    }
    defer db.Close()

    // Test the connection
    if err := db.Ping(); err != nil {
        panic(fmt.Errorf("failed to ping database: %v", err))
    }

    // Your insert logic here (hardcoded value as you mentioned)
    _, err = db.Exec("INSERT INTO your_table (column) VALUES (?)", "hardcoded_value")
    if err != nil {
        panic(fmt.Errorf("failed to insert: %v", err))
    }

    fmt.Println("Insert successful!")
}

3. Clean up your CI variables

You have a couple of issues in your variables section:

  • MYSQL_ADDRESS: "127.0.0.1:3306" is incorrect—remove this, since we're using the service hostname instead.
  • There's a typo: MYSQL_TRANSAPORT should be MYSQL_TRANSPORT (if you actually use this variable in your code; if not, you can remove it entirely).

Here's the corrected variables block:

variables:
  MYSQL_DATABASE: storage
  MYSQL_ROOT_PASSWORD: root
  MYSQL_HOST: mysql
  MYSQL_USER: root
  MYSQL_TRANSPORT: tcp # Fixed typo

4. Wait for MySQL to be ready

Sometimes the MySQL service takes a few seconds to fully start up before accepting connections. Add a step to your script to wait for the port to be open:

job:
  script:
    # Install netcat to check the port
    - apt-get update -qq && apt-get install -y netcat
    # Wait until MySQL is reachable
    - while ! nc -z $MYSQL_HOST 3306; do sleep 1; echo "Waiting for MySQL to start..."; done
    # Run your Go app (adjust the command to match your setup)
    - go run main.go

Putting all these changes together should get your Go app connecting to MySQL successfully in GitLab CI. The core issue was confusing localhost in the job container with the separate service container—using the service name as the hostname fixes that.

内容的提问来源于stack exchange,提问作者Nderim Xhemajli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:01:40