要运行一个程序,它要求是 MySQL 5.7 的版本。我是 Windows 机器,不想安装 MySQL,而是希望通过 Docker 来运行。这样以后机器想要哪个版本就运行哪个版本,方便灵活。同时,为了避免 Docker 重启后数据丢失,我将数据文件挂载到本机。
第一步:本机的配置
• 安装 Docker
确保 Docker 已安装并正常运行。
• 配置文件目录
• 配置文件目录:D:\home\dockerdata\mysql\cnf
• 日志文件目录:D:\home\dockerdata\mysql\logs
• 数据文件目录:D:\home\dockerdata\mysql\data
• 编辑配置文件

文件名称:my.cnf,放在D:\home\dockerdata\mysql\cnf。配置文件内容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Copyright (c) 2014, 2016, 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
# [MySQL Server System Variables](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
#log-error = /var/log/mysql/error.log
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0

max_connections = 2000
max_user_connections = 1900
max_connect_errors = 100000
max_allowed_packet = 50M
lower_case_table_names=1

[mysqld]
skip-name-resolve
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

第二步:拉取和运行镜像

• 拉取镜像

先拉取 MySQL 5.7 的镜像(也可以直接运行,如果没有镜像会自动拉取):

1
docker pull mysql:5.7

• 运行容器

运行 MySQL 容器,并挂载配置文件、日志文件和数据文件:

1
2
3
4
5
6
7
docker run -p 3306:3306 \
--name mysql2.0 \
-v D:\home\dockerdata\mysql\cnf\my.cnf:/etc/mysql/my.cnf \
-v D:\home\dockerdata\mysql\logs:/logs \
-v D:\home\dockerdata\mysql\data:/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=root \
-d mysql:5.7

第三步:连接到 MySQL 服务

• 使用 MySQL 客户端连接

使用 MySQL 客户端工具(如 MySQL Workbench 或命令行工具)连接到 MySQL 服务:

• 主机地址:127.0.0.1

• 端口:3306

• 用户名:root

• 密码:root

注意事项

• 确保路径中的目录(如D:\home\dockerdata\mysql\cnfD:\home\dockerdata\mysql\logsD:\home\dockerdata\mysql\data)已创建。

• 如果路径中包含空格,请确保路径用双引号括起来。

• 如果需要修改配置文件,可以编辑D:\home\dockerdata\mysql\cnf\my.cnf文件,然后重启容器。

通过以上步骤,你可以在 Windows 上使用 Docker 运行 MySQL 5.7,并将配置文件、日志文件和数据文件安全地挂载到本机。