用Docker搭建MySQL

1. 拉取镜像

docker pull mysql:latest

2. 建立相关目录

建立配置、数据、日志目录

mkdir -p /mysql_test/mysql/config
mkdir -p /mysql_test/mysql/data
mkdir -p /mysql_test/mysql/log

修改log目录的所属用户,其实data也是要改的,但是data会自动改。

cd /mysql_test/mysql
sudo chown 999 log

3. 建立配置文件

cd /mysql_test/mysql/config
vim my.cnf

my.cnf内容,这里只配了个错误日志路径

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/8.0/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M

# Remove leading # to revert to previous value for default_authentication_plugin,
# this will increase compatibility with older clients. For background, see:
# https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_default_authentication_plugin
# default-authentication-plugin=mysql_native_password
skip-host-cache
skip-name-resolve
log-error=/var/log/mysql/error.log

4. 建个密码配置文件,为了docker启动脚本中不出现密码明文

mkdir -p /mysql_test/mysql/config/secrets
echo "1234567" > /mysql_test/mysql/config/secrets/password

5. 编写启动脚本

vim run_mysql_test2.sh

脚本内容

docker run --name mysql_test2 \
        -h mysql_test2 \
        -p 0.0.0.0:4000:3306 \
        -v /mysql_test/mysql/config:/etc/mysql/conf.d \
        -v /mysql_test/mysql/data:/var/lib/mysql \
        -v /mysql_test/mysql/log:/var/log/mysql \
        -e MYSQL_ROOT_PASSWORD_FILE=/etc/mysql/conf.d/secrets/password \
        --restart=always \
        -d mysql:latest \

脚本解读

--name mysql_test2 # 容器名
-h mysql_test2 # 容器host名
-p 0.0.0.0:4000:3306 # 端口映射
-v /mysql_test/mysql/config:/etc/mysql/conf.d # 配置文件目录映射
-v /mysql_test/mysql/data:/var/lib/mysql # 数据目录映射
-v /mysql_test/mysql/log:/var/log/mysql # 日志目录映射
-e MYSQL_ROOT_PASSWORD_FILE=/etc/mysql/conf.d/secrets/password # 指定root密码文件
--restart=always # 随docker启动
-d mysql:latest # 后台启动mysql:latest

6. 启动容器

sh run_mysql_test2.sh

7.连接数据库

这里使用的是Navicat工具,Navicat安装可以参考https://www.bilibili.com/read/cv17235251

新建mysql链接,填入连接名、地址、端口、用户名、密码


image.png

测试连接,显示连接成功就ok了


image.png

你可能感兴趣的:(用Docker搭建MySQL)