查询docker mysql版本
docker search mysql
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
mysql MySQL is a widely used, open-source relation… 12738 [OK]
安装
docker pull mysql:8.0.23
8.0.23: Pulling from library/mysql
f7ec5a41d630: Pull complete
Digest: sha256:6e0014cdd88092545557dee5e9eb7e1a3c84c9a14ad2418d5f2231e930967a38
Status: Downloaded newer image for mysql:8.0.23
docker.io/library/mysql:8.0.23
启动mysql
先创建/docker_data/mysql/conf/my.cnf文件
mkdir -p /docker_data/mysql/conf/
vim /docker_data/mysql/conf/my.cnf
[client]
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
[mysqld]
character-set-server=utf8mb4
default_authentication_plugin=mysql_native_password
运行mysql并挂载卷到宿主机
docker run -d -p 3306:3306 --privileged=true --restart=always -v /docker_data/mysql/data:/var/lib/mysql -v /docker_data/mysql/conf:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=123456 --name mysql-8.0.23 mysql:8.0.23
如果是docker desktop,则为以下命令
docker run -d -p 3306:3306 --restart=always -e MYSQL_ROOT_PASSWORD=123456 --name mysql-8.0.23 mysql:8.0.23 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
开放防火墙端口
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --reload
exec进入容器,登录mysql,创建用户和密码,授权,刷新。
[root@node1 host_data]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
3b9f3b3ad3a6 mysql:8.0.23 "docker-entrypoint.s…" About a minute ago Up About a minute 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp, 33060/tcp mysql-8.0.23
fada3bfc9c0d ubuntu "bash" 3 hours ago Up 3 hours u1
0bc3e60b4e1f registry "/entrypoint.sh /etc…" 5 hours ago Up 5 hours 0.0.0.0:5000->5000/tcp, :::5000->5000/tcp registry
[root@node1 host_data]# docker exec -it mysql-8.0.23 bash
root@3b9f3b3ad3a6:/# mysql -uroot -p123456
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 53
Server version: 8.0.23 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#新建用户
mysql> CREATE USER 'x'@'%' IDENTIFIED WITH mysql_native_password BY 'x' PASSWORD EXPIRE NEVER;
#授权新用户
mysql> GRANT all on *.* to 'x'@'%';
#刷新新用户
mysql> FLUSH PRIVILEGES;
#退出mysql
mysql> exit;
navicat测试连接(前提是服务器开放了3306端口或关闭了防火墙)
挂载卷以后,就算别人不小心把你的mysql删掉了,也可以通过docker run -d -p 3306:3306 --privileged=true -v /docker_data/mysql/log:/var/log/mysql -v /docker_data/mysql/data:/var/lib/mysql -v /docker_data/mysql/conf:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=123456 --name mysql-8.0.23 mysql:8.0.23重新安装回来,数据也不会丢失。