1、构建mysql镜像(基于官方镜像)
1. 时间不同步(原因)
在使用docker创建mysql容器是,发现容器中的时间和宿主机系统时间(当前时间)相差了8小时,经过不断调试:
- 设置mysql容器的系统时间:
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
- 设置mysql数据库中的时间:
default-time_zone = '+8:00'
“日志驱动和存储时间是分开的 估计时区也是分开配置” — 来自大佬的话术
根据大佬的提供方案,使数据库日志时间跟随系统:set global log_timestamps=SYSTEM
上面的命令仅在数据库中设置全局变量,为临时配置,当数据库重启之后还是会恢复时间,永久配置可以修改配置文件的[mysqld]
中添加相关参数:log_timestamps=SYSTEM
2. 镜像构建
mysql.cnf
vim mysqld.cnf
# Copyright (c) 2014, 2021, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0,
# as published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# but not limited to OpenSSL) that is licensed under separate terms,
# as designated in a particular file or component or in included license
# documentation. The authors of MySQL hereby grant you an additional
# permission to link the program and your derivative works with the
# separately licensed software that they have included with MySQL.
#
# 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, version 2.0, 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
#log-error = /var/log/mysql/error.log
# By default we only accept connections from localhost
#bind-address = 127.0.0.1
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# mysql日志时间跟随系统时间
log_timestamps=system
#default-time_zone = '+8:00'
Dockerfile
FROM mysql:5.7
MAINTAINER "Geray <1690014753@qq.com>"
COPY mysqld.cnf /etc/mysql/mysql.conf.d/
RUN set -eux; \
rm -rf /etc/localtime && \
ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
构建:
sudo docker build -t geray/mysql:5.7-v1 .
sudo docker push geray/mysql:5.7-v1
部署
mkdir /mysql/{etc,data,logs} -p
docker run -d -p 3306:3306 --name=mysql \
--mount type=bind,src=/mysql/data,dst=/var/lib/mysql \
-e MYSQL_ROOT_PASSWORD=Geray@2022 \
--restart always \
geray/mysql:5.7-v1
登陆容器进行mysql操作
docker exec -it mysql /bin/bash
mysql -uroot -p
# 或者直接docker命令登陆(第一个mysql是容器名称,第二个mysql是命令)
docker exec -it mysql mysql -uroot -p
2、docker容器中系统和本机时间不同步
默认官方使用的系统时间是UTC,国际标准时间,而我们的时间使用的是CST,相差了8小时,所以查看时间时会发现存在8小时误差
1. 容器启动时设置参数
-e TZ=Asia/Shanghai
2. 挂载宿主机时间文件到容器
-v /etc/localtime:/etc/localtime:ro