一、下载mysql镜像
docker pull mysql
二、启动mysql无效
[root@localhost ~]# docker run --name mysql01 -d mysql
42f09819908bb72dd99ae19e792e0a5d03c48638421fa64cce5f8ba0f40f5846
mysql退出了
[root@localhost ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
42f09819908b mysql "docker-entrypoint.sh" 34 seconds ago Exited (1) 33 seconds ago mysql01
538bde63e500 tomcat "catalina.sh run" About an hour ago Exited (143) About an hour ago compassionate_
goldstine
c4f1ac60b3fc tomcat "catalina.sh run" About an hour ago Exited (143) About an hour ago lonely_fermi
81ec743a5271 tomcat "catalina.sh run" About an hour ago Exited (143) About an hour ago sick_ramanujan
//错误日志
[root@localhost ~]# docker logs 42f09819908b
error: database is uninitialized and password option is not specified
You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD;这个三个参数必须指定一个
三、正确的启动
[root@localhost ~]# docker run --name mysql01 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
b874c56bec49fb43024b3805ab51e9097da779f2f572c22c695305dedd684c5f
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b874c56bec49 mysql "docker-entrypoint.sh" 4 seconds ago Up 3 seconds 3306/tcp mysql01
四、做端口映射启动
[root@localhost ~]# docker run -p 3306:3306 --name mysql02 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
ad10e4bc5c6a0f61cbad43898de71d366117d120e39db651844c0e73863b9434
[root@localhost ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ad10e4bc5c6a mysql "docker-entrypoint.sh" 4 seconds ago Up 2 seconds 0.0.0.0:3306->3306/tcp mysql02
五、常见问题
一般端口映射之后就可以远程访问了,但是有一些是无法远程连接数据库的
原因:
mysql8 之前的版本中加密规则是mysql_native_password,但是在mysql8之后,加密规则是caching_sha2_password,
所以 连接数据库工具 低版本不支持了,要么升级 连接数据库工具,要么把用户密码登录的加密规则还原成mysql_native_password这种加密方式
步骤:
首先进入docker中的mysql容器
// ec9d0d788590是mysql容器的id,docker ps -a 查看正在运行的容器信息
[root@localhost]# docker exec -it ec9d0d788590bash
进去容器后,进行mysql登入,登入成功后,执行以下两条命令更改加密规则
ALTER USER ‘root‘@‘%‘ IDENTIFIED WITH mysql_native_password BY ‘你的密码‘;
ALTER USER ‘root‘@‘localhost‘ IDENTIFIED WITH mysql_native_password BY ‘你的密码‘;
连接成功
原文:https://www.cnblogs.com/zhou-pan/p/10452634.html