gpt4 book ai didi

mysql - 从主机连接到 docker mysql

转载 作者:行者123 更新时间:2023-11-29 01:19:39 26 4
gpt4 key购买 nike

我有 docker-compose(只显示 MySQL 部分):

  site_mysql:
image: site/mysql:latest
build: ./images/mysql
environment:
MYSQL_ROOT_PASSWORD: secret
volumes:
- site_mysqldata:/var/lib/mysql
networks:
- site_appnet
ports:
- "3306:3306"

我可以从容器内部连接到 MySQL,但我不能从本地主机连接,我得到的错误是Host site_mysql is unknown。

docker 文件是:

FROM mysql:5.7

MAINTAINER Author

# The official MySQL docker image will run all .sh and .sql scripts found in this directory
# the first time the container is started.
COPY init.sql /docker-entrypoint-initdb.d
COPY my.cnf /etc/mysql/conf.d

我的.cnf:

[mysqld]
# Always use UTC
default-time-zone='+00:00'

# To turn off strict mode (alas, we started out that way, will be work to turn it on)
sql-mode="NO_ENGINE_SUBSTITUTION"

max-allowed-packet = 16M

### Per-thread Buffers
sort-buffer-size = 2M
read-buffer-size = 128K
read-rnd-buffer-size = 256K
join-buffer-size = 256K

### Temp Tables
tmp-table-size = 64M
max-heap-table-size = 64M

#### Storage Engines
default-storage-engine = InnoDB
innodb = FORCE

初始化.sql :

CREATE DATABASE IF NOT EXISTS site;
CREATE DATABASE IF NOT EXISTS site_test;
CREATE USER 'site'@'%' IDENTIFIED BY 'secret';
GRANT ALL PRIVILEGES ON site.* TO 'site'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

我在不同的项目中使用相同的配置一段时间,直到现在一切正常。知道为什么我的主机无法识别 site_mysql 吗?

已更新

此外,我还有:

  site_memcached:
image: memcached:1.4-alpine
networks:
- videosite_appnet

在这里我可以使用 site_memcached 作为主机名进行连接

最佳答案

如果从主机连接,则必须使用“localhost”而不是“site_mysql”

site_mysql: --> this is the servername within docker
image: site/mysql:latest
build: ./images/mysql
environment:
MYSQL_ROOT_PASSWORD: secret
volumes:
- site_mysqldata:/var/lib/mysql
networks:
- site_appnet
ports:
- "3306:3306" --> here you open
port 3306 also on localhost (your host computer)
and bind it to the containers port 3306

我的个人配置(mac 主机)是:(也许“重启:总是”有帮助)

db:
image: "mysql:5"
ports:
- "3306:3306"
networks:
- main
volumes:
- ./mysql/config:/etc/mysql/conf.d:cached
- ./mysql/data:/var/lib/mysql:cached
- ./mysql/init:/docker-entrypoint-initdb.d:cached
restart: always
environment:
TZ: UTC
MYSQL_ROOT_PASSWORD: somepassword

关于mysql - 从主机连接到 docker mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968871/

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