我有一个mysql数据库,运行了以下docker-compose.yml:
version: '3.3'
services:
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: 'demo'
# So you don't have to use root, but you can if you like
MYSQL_USER: 'user'
# You can use whatever password you like
MYSQL_PASSWORD: 'password'
# Password for root access
MYSQL_ROOT_PASSWORD: 'password'
ports:
# : < MySQL Port running inside container>
- '3306:3306'
expose:
# Opens port 3306 on the container
- '3306'
# Where our data will be persisted
volumes:
- my-db:/var/lib/mysql
networks:
- backend
networks:
backend:
driver: bridge
# Names our volume
volumes:
my-db:$ docker-compose build
$ docker-compose up
我使用以下Dockerfile提供了一个基本的golang:
# Start from golang:1.12-alpine base image
FROM golang:1.12-alpine
# Adding git, bash and openssh to the image
RUN apk update && apk upgrade && \
apk add --no-cache bash git openssh
# Set the Current Working Directory inside the container
WORKDIR /app
# Copy the source from the current directory to the Working Directory inside the container
COPY . .
RUN go get -d github.com/gorilla/mux
RUN go get -d github.com/go-sql-driver/mysql
RUN go get -d github.com/golang-migrate/migrate
RUN go get -d github.com/golang-migrate/migrate/database/mysql
RUN go get -d github.com/golang-migrate/migrate/source/file
# Build the Go app
RUN go build -o main .
# Expose port 8080 to the outside world
EXPOSE 8080
# Run the executable
CMD ["./main"]以下函数称为:
func CreateDatabase() (*sql.DB, error) {
serverName := "localhost:3306"
user := "user"
password := "password"
dbName := "demo"
connectionString := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=true&multiStatements=true", user, password, serverName, dbName)
db, err := sql.Open("mysql", connectionString)
if err != nil {
return nil, err
}
if err := migrateDatabase(db); err != nil {
return db, err
}
return db, nil
}$ docker run -p 80:8080 --network=-mysql_backend
$ Database connection failed: %sdial tcp 127.0.0.1:3306: connect: connection refused
我无法获得api来与数据库容器建立数据库连接?
发布于 2020-01-25 05:26:54
您的golang应该包含在撰写文件中,并添加到同一个网络中。
当您运行golang时,您还会将它添加到backend以外的网络中,后者是在您的撰写文件中创建的网络。
发布于 2020-02-07 13:12:27
除了将app容器连接到同一个backend网络之外,还需要在连接字符串中修复MySQL主机参数。
查看main函数,将MySQL主机设置为localhost
serverName := "localhost:3306"
但是,MySQL没有监听appc容器的lcoalhost,您需要在复合文件(即db )中将其更改为MySQL服务名称。
https://devops.stackexchange.com/questions/10591
复制相似问题