前段时间一直在折腾docker数据挂载的问题
docker-compose不熟悉的同学可以先看看我上一篇和docker-compose相关的博客:docker-compose搭建个人博客
0x00 功能需求
- 能够使用
docker-compose
一键开启/停止,一键生成/删除 - 数据持久化,能够在宿主机中修改容器设置
0x01 设计思路
- 要完成一键式服务,就必须在
docker-compose.yml
中写完全部的配置信息 - 修改容器配置,需要给数据库配置文件
/etc/mysql/my.cnf
做映射(mysql8,低版本的mysql需要修改映射地址)
0x02 代码实现
创建docker-compose
文件,并创建conf
文件夹,在conf
文件夹内创建my.cnf
文件

./docker-compose.yml
version: '3'
services:
mysql:
restart: always
image: mysql:latest
# 选择镜像,这里用的是mysql8,低版本mysql需要修改配置文件映射地址
container_name: my_mysql
volumes:
- ./mydir:/mydir
# 文件挂载
- ./datadir:/var/lib/mysql
# 挂载目录
- ./conf/my.cnf:/etc/mysql/my.cnf
# 挂载 my.cnf 配置文件
- ./docker/mysql/source:/docker-entrypoint-initdb.d
environment:
- "MYSQL_ROOT_PASSWORD=xxxx"
# 设置密码
- "MYSQL_DATABASE=mydb"
# 设置默认数据库
- "TZ=Asia/Shanghai"
# 设置时区
ports:
- 3306:3306
# 设置端口
./conf/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
# skip-grant-tables
# 不使用密码
secure-file-priv=NULL
# 设置FILE权限
# Custom config should go here
!includedir /etc/mysql/conf.d/
0x03 运行方法
docker-compose up -d
# 创建容器
docker-compose down
# 删除容器
docker-compose start
# 开始运行
docker-compose stop
# 结束运行
直接修改宿主机中的my.cnf
即可修改容器数据库的配置
查看运行结果:

进入容器:
docker exec -it my_mysql /bin/bash
# 这里的my_mysql是docker-compose里面设置的容器名
mysql -u root -p
# 输入密码进入mysql终端

Comments | NOTHING