我将Api与在容器中运行的MySQL数据库连接时遇到问题。我有用于Golang Api的Dockerfile:
FROM golang:latest
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
WORKDIR /app/bin
EXPOSE 8080
RUN go run ./../cmd/web/
我通常使用数据库/ sql连接应用程序中的数据库:
dsn = "user1:pass@tcp(wpmysql:3306)/wp?parseTime=true"
db, err := sql.Open("mysql", dsn)
我的docker-compose.yml:
version: '3'
services:
db:
image: mysql:5.7
container_name: ${MYSQL_CONTAINER_NAME}
ports:
- 3306:3306
command: --init-file /usr/src/app/init.sql
volumes:
- ./init.sql:/usr/src/app/init.sql
environment:
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASS}
- MYSQL_DATABASE=${MYSQL_DB}
- MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
networks:
- fullstack
web:
container_name: wpapi
build: .
ports:
- 8080:8080
restart: on-failure
volumes:
- .:/usr/src/app/
depends_on:
- db
networks:
- fullstack
networks:
fullstack:
driver: bridge
与docker-compose.yml在同一目录中是文件.env:
DB_PASSWORD=pass
MYSQL_PORT=3306
MYSQL_USER=user1
MYSQL_PASS=pass
MYSQL_DB=wp
MYSQL_CONTAINER_NAME=wpmysql
通话后称赞:
$ docker-compose up -d db
$ docker-compose build web
我收到错误ERROR main.go:46: dial tcp: lookup wpmysql on 37.8.214.2:53: no such host
。容器列表如下所示:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9fbaf67df5bf 2778fcda2046 "/bin/sh -c 'go run …" 14 seconds ago Up 13 seconds 8080/tcp mystifying_shannon
7f6c76cc9c4f mysql:5.7 "docker-entrypoint.s…" 40 minutes ago Up About a minute 0.0.0.0:3306->3306/tcp, 33060/tcp wpmysql
此外,当我尝试通过dsn = "user1:pass@tcp(localhost:3306)/wp?parseTime=true"
或dsn = "root:pass@tcp(localhost:3306)/wp?parseTime=true"
连接应用程序时,出现另一个错误:dial tcp 127.0.0.1:3306: connect: connection refused
尽管我可以使用docker exec -it wpmysql bash -l
和sign in
凭据进入容器(root
)和user1
]
我将Api与在容器中运行的MySQL数据库连接时遇到问题。我有用于Golang Api的Dockerfile:FROM golang:latest WORKDIR / app COPY go.mod go.sum ./ RUN go mod下载COPY。 。 ...
我收到错误ERROR main.go:46:拨打tcp:在上查找wpmysql37.8.214.2:53:没有这样的主机。容器列表如下所示: