首先进入安装mysql的目录,没有就自行创建
mkdir -p /usr/local/docker/mysql-docker
cd /usr/local/docker/mysql-docker
接着挂载目录
# 选择自己的软件安装目录,新建挂载文件目录
mkdir -p data logs mysql-files conf
# 赋予权限、这里我自己用为了方便直接设置了777,如果你要求安全,请不要如此设置,
# 需根据挂载文件要求的权限放开对应的读、写或执行权限即可
chmod 777 data logs mysql-files conf
进入conf目录并创建并配置my.cnf
cd conf
vi my.cnf
[mysqld]
user=mysql
bind-address = 0.0.0.0 # 表示允许任何主机登陆MySQL
port=3306 # 表示MySQL运行端口为3306
default-storage-engine=INNODB
#character-set-server=utf8
character-set-client-handshake=FALSE
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4'
secure-file-priv=
[client]
#utf8mb4字符集可以存储emoji表情字符
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
最新版本的镜像可参照官网
https://dev.mysql.com/doc/relnotes/mysql/8.0/en/
进入安装目录并创建docker-compose.yaml
cd /usr/local/docker/mysql-docker
vi docker-compose.yaml
version: "3"
services:
mysql:
image: mysql:8.0.33
container_name: mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
ports:
- 13306:3306
command:
--default-authentication-plugin=mysql_native_password
--lower_case_table_names=1
--character-set-server=utf8mb4
--collation-server=utf8mb4_general_ci
--wait_timeout=28800
--interactive_timeout=28800
--max_connections=1000
--explicit_defaults_for_timestamp=true
--max_allowed_packet=128M
volumes:
- /etc/localtime:/etc/localtime
- ./data:/var/lib/mysql
- ./conf/my.cnf:/etc/mysql/my.cnf
- ./logs:/var/log/mysql
- ./mysql-files:/var/lib/mysql-files
参数说明:
注意需要在docker-compose.yml所在的目录下执行
docker-compose -f docker-compose.yaml up -d
查看是否启动成功
docker ps
如果启动失败,查看日志
docker-compose logs -f
# 进入mysql容器
docker exec -it mysql bash
# 登录mysql
mysql -u root -p
# 提示输入密码root,直接enter即可
# 使用mysql数据库
use mysql;
# 查询mysql账户表信息
select user, host, authentication_string, plugin from user;
# 修改host可以远程访问
UPDATE mysql.user SET Host='%' WHERE User='root' AND Host='localhost';
# 刷新权限
FLUSH PRIVILEGES;
# 修改root密码
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'root';
# 刷新权限
FLUSH PRIVILEGES;
# 退出mysql,退出容器
exit;
重启mysql容器
# 重启mysql容器
cd /usr/local/docker/mysql-docker;
docker-compose restart;
# 此时root账号可以远程访问了
查看日志:
docker-compose logs -f
或者新建一个用户(推荐)
CREATE USER 'fuyun'@'%' IDENTIFIED BY 'T@#^%HKGYjhds9123HJ';
GRANT ALL PRIVILEGES ON *.* TO 'fuyun'@'%';
FLUSH PRIVILEGES;
iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 13306 -j ACCEPT
systemctl restart firewalld