环境背景:
IP | os |
---|---|
192.168.0.15 | centos 7.9.2009 |
下载镜像
docker pull mysql/mysql-server:5.7
启动
docker run -d -p3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=mypasswd mysql/mysql-server:5.7 --character-set-server=utf8 --collation-server=utf8_general_ci
查看密码
docker logs mysql|grep PASSWORD
[Entrypoint] GENERATED ROOT PASSWORD: QOLSexup)4xAPYK$aDOccELegOJ
进入数据库更新密码
docker exec -it mysql mysql -uroot -p
alter user 'root'@'localhost' identified by 'rootmysqlpasswd';
或者
set password for 'root'@'localhost'=PASSWORD('rootmysqlpasswd');
授权账号
grant all privileges on *.* to 'root'@'%' identified by "rootpasswd";
flush privileges;
查看容器IP信息
docker inspect mysql|jq
"IPAddress": "172.17.0.4",
安装一个mysql客户端
yum install mysql -y
测试连接容器mysql
mysql -uroot -p -h172.17.0.4
建立几条测试数据
create database mytestdb;
use mytestdb;
create table table1 (id int not null auto_increment primary key,name char(32));
insert into table1 values (1,"zhangsan");
insert into table1 values (2,"lisi");
查看mysql容器存储路径
[root@kafka1 ~]# docker inspect mysql1|jq '.[].Mounts'
[
{
"Type": "volume",
"Name": "3b10d8865099277040989c1465cadb43cbd20a47d7c2115834f01537926a1725",
"Source": "/var/lib/docker/volumes/3b10d8865099277040989c1465cadb43cbd20a47d7c2115834f01537926a1725/_data",
"Destination": "/var/lib/mysql",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
]
Destination 容器内部存储路径:/var/lib/docker/volumes/3b10d8865099277040989c1465cadb43cbd20a47d7c2115834f01537926a1725/_data
Source 宿主机路径:/var/lib/mysql
docker run -v "/opt/docker/mysql/data/":/var/lib/mysql -p3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=mypasswd mysql/mysql-server:5.7
docker exec some-mysql sh -c 'exec mysqldump --all-databases -uroot -p"$MYSQL_ROOT_PASSWORD"' > /some/path/on/your/host/all-databases.sql
docker exec -i some-mysql sh -c 'exec mysql -uroot -p"$MYSQL_ROOT_PASSWORD"' < /some/path/on/your/host/all-databases.sql
下面高版本docker服务用的
官方推荐持久化启动命令
docker run --name=mysql1 \
--mount type=bind,src=/path-on-host-machine/my.cnf,dst=/etc/my.cnf \
--mount type=bind,src=/path-on-host-machine/datadir,dst=/var/lib/mysql \
-d mysql/mysql-server:tag
mkdir -p /opt/docker/mysql/etc/
mkdir -p /opt/docker/mysql/data/
docker cp mysql1:/etc/my.cnf /opt/docker/mysql/etc/
docker cp mysql1:/etc/my.cnf.d /opt/docker/mysql/etc/
docker cp mysql1:/var/lib/mysql /opt/docker/mysql/data/
docker stop mysql1
docker rm mysql1