gpt4 book ai didi

mysql - 无法从 Golang 容器连接到 MySQL 容器

转载 作者:行者123 更新时间:2023-11-29 06:27:34 26 4
gpt4 key购买 nike

我有 2 个容器:一个简单的 golang 程序和 mysql。我可以启动两者,但 golang 应用程序无法连接到 mysql。我收到连接被拒绝

如果我docker exec进入 mysql 容器并尝试使用 mysql -u root -p 进行本地连接一切正常。

如果在主机上我尝试使用 mysql -h 0.0.0.0 -P 10000 -u root -p 连接到容器一切正常。

我添加了MYSQL_ROOT_HOST: '%'docker-composebind-address = 0.0.0.0进入mysqld.cnf但仍然无法正常工作。

我做错了什么?

docker-compose

    version: '3'
services:
web:
build:
context: .
dockerfile: docker/web/Dockerfile
ports:
- "8081:8081" # http
- "443:443" # https
links:
- db_private
volumes:
- ../../../../.:/go
db_private:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: ${MYSQL_DATABASE}
MYSQL_USER: ${MYSQL_USER}
MYSQL_PASSWORD: ${MYSQL_PASSWORD}
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_ROOT_HOST: '%'
ports:
- '10000:3306'
expose:
- '3306'
volumes:
- ./mysql-entry-point.sql:/docker-entrypoint-initdb.d
- private-db:/var/lib/mysql
- ./mysqld.cnf:/etc/mysql/mysql.conf.d/mysqld.cnf
# Names our volume
volumes:
private-db:

Web 容器 Dockerfile

    FROM golang:alpine
RUN mkdir /app
ADD . /app/

WORKDIR /app

RUN apk update && apk upgrade && apk add --no-cache bash git openssh

RUN go get github.com/jinzhu/gorm
RUN go get github.com/jinzhu/gorm/dialects/mysql
RUN go get github.com/gin-gonic/gin
RUN go get github.com/gin-contrib/cors


RUN go build -o main .
RUN adduser -S -D -H -h /app appuser
USER appuser
CMD ["./main"]

Golang 文件

    package main

import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"net/http"
"time"
)

var db *gorm.DB

type (
FooModel struct {
Id int64 `gorm:"primary_key"`
name string
}
)

func init() {
//open a db connection
var err error
db, err = gorm.Open("mysql", "user:pwd@(0.0.0.0:10000)/myDB?charset=utf8&parseTime=true")
if err != nil {
fmt.Println(err)
panic("failed to connect database")
}
//Migrate the schema
db.AutoMigrate(&FooModel{})

db.LogMode(true)
}

// main inits routes
func main() {

router := gin.Default()

router.GET("/getExample", getExample)

router.Run("0.0.0.0:8081")
}


func getExample(c *gin.Context) {

c.JSON(http.StatusOK, gin.H{"status": http.StatusOK, "data": "bye"})
}

我复制 mysqld.cnf在装有此的容器中

    [mysqld]
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
datadir = /var/lib/mysql
#log-error = /var/log/mysql/error.log
# By default we only accept connections from localhost
#bind-address = 127.0.0.1
bind-address = 0.0.0.0
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

最佳答案

您的 Web 应用程序在容器中运行,这意味着地址 0.0.0.0 是容器本身,而不是其运行的主机。尝试使用 db_private 名称而不是地址 0.0.0.0 连接数据库。

关于mysql - 无法从 Golang 容器连接到 MySQL 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58614060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com