【日常记录-Docker】构建自定义MySQL镜像

Author:赵志乾
Date:2024-08-02
Declaration:All Right Reserved!!!

1. 概述

自定义MySQL镜像,使其在启动时执行指定的SQL脚本;

2. 文件说明

总共3个文件:my.cnf、db.sql、Dockerfile,且三个文件放在同一个目录。

mysql的配置文件,文件名为my.cnf,内容如下:

[client]
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
[mysqld]
init_connect='SET collation_connection = utf8mb4_unicode_ci'
init_connect='SET NAMES utf8mb4'
default_authentication_plugin = mysql_native_password
default-time-zone='+08:00'
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
expire_logs_days=1
skip-character-set-client-handshake
skip-name-resolve
secure_file_priv=null
skip-log-bin

自定义sql文件,文件名为db.sql,内容如下:

#创建数据库
create database if not exists mydb;
#切换数据库
use mydb;
#创建数据表
create table if not exists `input_data` (
    `id`          bigint(20)    unsigned   not null auto_increment,
    `task_id`     varchar(50)              not null    default '0'   comment '任务id',
    `iteration`   int(10)                  not null    default 0     comment '迭代次数',
    `value`       longblob                 not null                  comment '数据内容',
    `create_time` datetime                 not null    default CURRENT_TIMESTAMP,
    `update_time` datetime                 not null    default CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    primary key             (`id`)                   using btree,
    unique index `uniq_idx` (`task_id`, `iteration`) using btree
)
comment = '输入数据'
collate ='utf8mb4_0900_ai_ci'
engine =InnoDB
auto_increment=1
;

Dockerfile内容如下:

FROM mysql:8.0.26

COPY my.cnf /etc/mysql/my.cnf
COPY db.sql /docker-entrypoint-initdb.d/db.sql
RUN chmod a+x /docker-entrypoint-initdb.d/db.sql

3. 镜像构建与容器运行

# 构建镜像
docker build --no-cache -f ./Dockerfile -t custommysql:8.0.26 .
# 运行容器
docker run -p 3308:3306 --name custommysql -e MYSQL_ROOT_PASSWORD=123456 -v /project/mysql:/var/lib/mysql -d --restart=always custommysql:8.0.26
相关推荐
破-风2 小时前
linux的用法
linux·运维·服务器
是小崔啊5 小时前
事务03之MVCC机制
数据库·mysql·事务·
大耳朵土土垚5 小时前
【Linux】日志设计模式与实现
linux·运维·设计模式
学问小小谢5 小时前
第26节课:内容安全策略(CSP)—构建安全网页的防御盾
运维·服务器·前端·网络·学习·安全
yaoxin5211236 小时前
第十二章 I 开头的术语
运维·服务器
ProgramHan6 小时前
1992-2025年中国计算机发展状况:服务器、电脑端与移动端的演进
运维·服务器·电脑
马立杰9 小时前
H3CNE-33-BGP
运维·网络·h3cne
Linux运维老纪9 小时前
DNS缓存详解(DNS Cache Detailed Explanation)
计算机网络·缓存·云原生·容器·kubernetes·云计算·运维开发
云空10 小时前
《DeepSeek 网页/API 性能异常(DeepSeek Web/API Degraded Performance):网络安全日志》
运维·人工智能·web安全·网络安全·开源·网络攻击模型·安全威胁分析
fajianchen11 小时前
MySQL 索引存储结构
数据库·mysql