1. 前期准备
新部署前可以从仓库(repository)下载 MySQL 镜像,或者从已有部署中的镜像生成文件:
代码语言:javascript复制# 查看当前本地镜像
docker images
# 生成本地镜像文件
docker save <IMAGE ID> -o mysql_8023.tar
2. 导入镜像
代码语言:javascript复制# 在新部署的机器上导入镜像
docker load -i mysql_8023.tar
docker images
3. 创建部署脚本文件
mysql-deploy.sh 文件内容如下:
代码语言:javascript复制#!/bin/bash
# 生成目录
mkdir -p /usr/local/docker/mysql/mysql-files
mkdir -p /usr/local/docker/mysql/conf
mkdir -p /usr/local/docker/mysql/logs
mkdir -p /usr/local/docker/mysql/data
# 将配置文件复制到相应目录
cp /root/my.cnf.template /usr/local/docker/mysql/conf/my.cnf
# 修改属主
chown -R polkitd:root /usr/local/docker/mysql/
# 创建容器
docker run -p 3306:3306
-v /usr/local/docker/mysql/mysql-files:/var/lib/mysql-files
-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=root
--name mysql
--restart=always
-e TZ=Asia/Shanghai
-d cbe8815cbea8
4. MySQL 服务器配置文件模板
my.cnf.template 文件内容如下:
代码语言:javascript复制[mysqld]
max_allowed_packet = 1G
explicit_defaults_for_timestamp=0
lower_case_table_names=1
log_timestamps=SYSTEM
sql_mode='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'
binlog_expire_logs_seconds=259200
secure_file_priv=''
log_bin_trust_function_creators=on
character-set-server = utf8mb4
default_authentication_plugin=mysql_native_password
datadir=/var/lib/mysql/
socket=/var/run/mysqld/mysqld.sock
wait_timeout=30
innodb_buffer_pool_size = 4G
max_connections = 1000
default-time-zone = ' 8:00'
port = 3306
skip-name-resolve
innodb_print_all_deadlocks=1
log_output='table'
server-id = 2955
innodb_max_dirty_pages_pct = 90
innodb_lock_wait_timeout = 120
gtid-mode = off
local_infile=0
log_error='/var/lib/mysql/master.err'
skip_symbolic_links=yes
[mysqldump]
quick
max_allowed_packet = 1G
[mysqld_safe]
open-files-limit = 8192
5. 执行脚本创建容器
代码语言:javascript复制./mysql-deploy.sh
6. 后续工作
代码语言:javascript复制# 进入容器
docker exec -it mysql /bin/bash
# 登录 MySQL
mysql -uroot -proot -S /var/lib/mysql/mysqld.sock
# 创建用户
create user dba identified by '123456';
grant all on *.* to dba with grant option;
7. 基本维护
代码语言:javascript复制# 查看镜像
docker images
# 查看容器
docker ps
# 查看容器详细信息
docker inspect <CONTAINER ID>
# 重启容器
docker restart mysql
# 停止容器
docker stop mysql
# 删除容器
docker rm mysql
# 进入容器
docker exec -it mysql /bin/bash
# 不进入容器执行 MySQL 命令行
docker exec -it mysql /bin/bash -c 'exec mysql -udba -p123456 -h127.0.0.1 -P3306' < dump.sql