1.下載鏡像
# docker從倉庫中拉取最新版的mysql鏡像,默認獲取最新的版本
docker pull mysql
2.創建掛載目錄
mkdir -p /home/docker/mysql/conf && mkdir -p /home/docker/mysql/datadir
3.新建my.cnf,保存
cd /home/docker/mysql/conf
vim my.cnf
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
# The MySQL Server configuration file.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
[mysqld]
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
datadir = /var/lib/mysql
secure-file-priv= NULL
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Custom config should go here
!includedir /etc/mysql/conf.d/
4.創建 MySQL 容器並啓動
解決了配置文件的問題,就可以根據需求創建我們的 MySQL 容器並掛載數據了。
docker run --name mysql8 \
-p 3306:3306 -e MYSQL_ROOT_PASSWORD=root \
--mount type=bind,src=/home/docker/mysql/conf/my.cnf,dst=/etc/mysql/my.cnf \
--mount type=bind,src=/home/docker/mysql/datadir,dst=/var/lib/mysql \
--restart=on-failure:3 \
-d mysql
- --name:爲容器指定一個名字
- -p:指定端口映射,主機端口:容器端口
- -e:pwd="xxx",設置環境變量
- --restart=on-failure:3:是指容器在未來出現異常退出(退出碼非0)的情況下循環重啓3次
- -mount:綁定掛載
- -d:後臺運行容器,並返回容器 id
5.登錄容器,修改mysql密碼
# 進入mysql 容器
docker exec -it mysql8 bash
# 進入mysql
mysql -uroot -p
# 輸入原本設置的密碼root
# 修改遠程登錄root密碼
ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'pwd';
# 修改登錄權限
grant all privileges on *.* to 'root'@'%' with grant option;
# 刷新數據庫
flush privileges;
# 退出數據庫
exit
# 退出容器
exit
6.遠程連接成功
參考:https://www.cnblogs.com/smallmin/p/11582954.html