发布于 

docker运行mysql

首先拉取MySQL镜像。

1
docker pull mysql:5.7.26

创建工作目录。

1
mkdir -p /data/mysql

部署MySQL。

1
docker run -p 3306:3306 --name mysql --restart=always -v /data/mysql/conf:/etc/mysql -v /data/mysql/logs:/logs -v /data/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=mysqlpwd -d mysql:5.7.26
  • -p 3306:3306 将容器的3306端口映射到主机的3306端口,第一个为主机端口,第二个为容器端口
  • --name mysql 启动后容器名为mysql。
  • -v /usr/local/workspace/mysql/conf:/etc/mysql 将主机/usr/local/workspace/mysql/conf目录挂载至容器的/etc/mysql,此为配置文件目录,建议挂载。
  • -v /usr/local/workspace/mysql/logs:/logs 同上,此为日志目录。
  • -v /usr/local/workspace/mysql/data:/var/lib/mysql 同上,此为数据文件目录,挂载后容器重启数据不会丢失,建议挂载。
  • -e MYSQL_ROOT_PASSWORD=mysqlpwd 设置root用户的密码。

默认开启远程登录,如无法登录,可进入容器开启。

1
2
docker ps | grep mysql
02d3bde85641 mysql:5.7.26 "docker-entrypoint.s…" 1 minutes ago Up 1 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysql

进入容器。

1
2
docker exec -it mysql /bin/bash
root@02d3bde85641:/#

登录MySQL并设置允许远程登录。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
root@02d3bde85641:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 564
Server version: 5.7.26 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

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> use mysql;
mysql> update user set authentication_string=password("mysqlpwd") where user="root";
mysql> FLUSH PRIVILEGES;
mysql> exit;

改密码也可能是下面这句。

1
mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'mysqlpwd' WITH GRANT OPTION;

然后即可愉快地连接 MySQL。