請參考個人另外一篇文章html
Docker 安裝及使用mysql
# 拉取最新版本鏡像 docker pull mysql # 拉取執行版本鏡像 docker pull mysql:版本號
docker images
docker run -d --name mysql --rm -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7 # -d 表明後臺運行 # -name 代碼容器名稱 # -p 表明端口映射,格式爲 宿主機映射端口:容器運行端口 # -e 表明添加環境變量 MYSQL_ROOT_PASSWORD是root用戶的登錄密碼
docker run -p 3306:3306 --name mysql-3307 \ -v /usr/local/docker/mysql/conf:/etc/mysql \ -v /usr/local/docker/mysql/logs:/var/log/mysql \ -v /usr/local/docker/mysql/data:/var/lib/mysql \ -e MYSQL_ROOT_PASSWORD=123456 \ -d mysql:latest # -v:主機和容器的目錄映射關係,":"前爲主機目錄,以後爲容器目錄
docker container ls # 能夠看到容器ID,容器的源鏡像,啓動命令,建立時間,狀態,端口映射信息,容器名字
sudo docker exec -it mysql bash mysql -uroot -p123456
咱們在建立容器的時候已經將容器的3306端口和主機的3306端口映射到一塊兒,因此咱們應該訪問:sql
host: 安裝mysql機器ip port: 3306 user: root password: 123456
# 開放端口: $ systemctl status firewalld $ firewall-cmd --zone=public --add-port=3306/tcp -permanent $ firewall-cmd --reload # 關閉防火牆: $ sudo systemctl stop firewalld
$ sudo docker exec -it mysql bash $ mysql -uroot -p123456 mysql> grant all privileges on *.* to root@'%' identified by "password";
原理:docker
# mysql使用mysql數據庫中的user表來管理權限,修改user表就能夠修改權限(只有root帳號能夠修改) mysql> use mysql; Database changed mysql> select host,user,password from user; +--------------+------+-------------------------------------------+ | host | user | password | +--------------+------+-------------------------------------------+ | localhost | root | *A731AEBFB621E354CD41BAF207D884A609E81F5E | | 192.168.1.1 | root | *A731AEBFB621E354CD41BAF207D884A609E81F5E | +--------------+------+-------------------------------------------+ 2 rows in set (0.00 sec) mysql> grant all privileges on *.* to root@'%' identified by "123456"; Query OK, 0 rows affected (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) mysql> select host,user,password from user; +--------------+------+-------------------------------------------+ | host | user | password | +--------------+------+-------------------------------------------+ | localhost | root | *A731AEBFB621E354CD41BAF207D884A609E81F5E | | 192.168.1.1 | root | *A731AEBFB621E354CD41BAF207D884A609E81F5E | | % | root | *A731AEBFB621E354CD41BAF207D884A609E81F5E | +--------------+------+-------------------------------------------+ 3 rows in set (0.00 sec)