1.3 docker 虚拟机与容器于互传文件,并制作二进制安装mysql5.7的镜像

二进制安装mysql优点:

  相对于docker下载官方mysql镜像安装,请看本目录下docker yum安装mysql章节。

1、自己设置mysql参数和文件地址。

2、可以设置Mysql文件保存地址。

3、能单独保存log日志,以便核查处理故障和后期维护。

缺点:

 1、安装完成后,镜像大于在4G,而官方Mysql镜像只有400M。

 2、安装方法复杂

  下来我们就开始安装。

一、准备环境

目录说明:

 [root@dockermysql] 此目录为登录到容器内的,容器目录

 [root@itpux docker] 此目录为虚拟机(母机)内的目录。

  当前要求是在虚拟机内安装mysql容器。

 

1.1 环境准备

    centos 7.4 64位,    docker pull 下载centos7。

[root@itpux docker]# docker pull centos
Using default tag: latest
Trying to pull repository docker.io/library/centos ... 
latest: Pulling from docker.io/library/centos
aeb7866da422: Pull complete 
Digest: sha256:67dad89757a55bfdfabec8abd0e22f8c7c12a1856514726470228063ed86593b
Status: Downloaded newer image for docker.io/centos:latest
[root@itpux docker]# 

 

   上传mysql 5.7二进制安装包mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz

 

1.2 下载镜像centos7后,进行镜像环境初始安装。

[root@itpux backup]# docker run -dit -p 3306:3306 -h dockermysql --name mysqldb centos7:v1 
f9dd85e9486a720493035e1dc22a79534f955cb27185cc7d365aa6e6dfe4b959
[root@itpux backup]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
f9dd85e9486a        centos7:v1          "/bin/bash"         3 seconds ago       Up 2 seconds        0.0.0.0:3306->3306/tcp   mysqldb
[root@itpux backup]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
centos7             v1                  75835a67d134        6 weeks ago         200.4 MB
[root@itpux backup]# 

 

 

二、文件上传

以下是将虚拟机文件上传到容器内,反之将容器拷到虚拟机。 

[root@useraddr mysql]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                    NAMES
49e7d6bb9ef7        centos7:v1          "/bin/bash"         43 minutes ago      Up 43 minutes       0.0.0.0:3306->3306/tcp   mysql
[root@useraddr mysql]# docker inspect -f '{{.Id}}' mysql
49e7d6bb9ef7d505318a9651a00d441c57549c7c1026ea10b5637e7804352872
[root@useraddr mysql]# docker cp mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz 49e7d6bb9ef7d505318a9651a00d441c57549c7c1026ea10b5637e7804352872:/docker/mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz
 [root@useraddr mysql]# 

 

三、环境检查

1.1 检查是否安装NySQL,如果安装 卸载之

rpm -qa |grep mysql
yum remove mysql*

 

1.2 检查是否安装MariaDB,如果安装 卸载之(重要)

rpm -qa |grep mariadb
yum remove mariadb*

 

1.3 新增用户/组/修改密码/修改参数文件

groupadd mysql
useradd -d /home/mysql -g mysql -m mysql

 

 1.4 解压、建立文件夹索引,方便知道系统版本号。

tar -xzvf mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz 
ln -s mysql-5.7.22-linux-glibc2.12-x86_64 mysql5.7
rm -rf mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz

  直接解压后,保留原文件夹命名,通过创建命名链接方式,以便后期版本管理和升级。

 

1.5 修改参数文件

vi ~/.bash_profile

PATH=$PATH:$HOME/.local/bin:$HOME/bin:/docker/mysql5.7/app/bin

--source执行后 ~/.bashrc 或者$. ~/.bashrc中的内容立即生效
source .bash_profile

 

1.5 规划目录 赋权限

mkdir -p /docker/mysql5.7/app
mv /docker/mysql5.7/* /docker/app/
mv /docker/app /docker/mysql5.7/
mkdir -p /docker/mysql5.7/data/3306/data
mkdir -p /docker/mysql5.7/log/3306/
mkdir -p /docker/mysql5.7/data/3306/run
mkdir -p /docker/mysql5.7/data/3306/tmp
touch /docker/mysql5.7/log/3306/mysql-error.log
touch /docker/mysql5.7/log/3306/mysql-general.log
touch /docker/mysql5.7/log/3306/mysql-slow.log

 1.6  安装vim包

[root@dockermysql docker]# yum install vim

 

四、将配置文件(my.cnf、mysql.serve)拷到容器对应mysql5.7目录,

4.1 上传配置文件到容器内

[root@dockermysql app]# pwd
/docker/mysql5.7/app
[root@dockermysql app]# mkdir cnf

 

编辑参数文件 my.cnf和mysql.server,详细配置请见后面内容,并将文件上传到容器的/docker/mysql5.7/app/cnf

 ---到母机上进行操作

[root@itpux docker]# ll
总用量 628732
-rw-r--r-- 1 root root     11613 11月 22 12:43 my.cnf
-rw-r--r-- 1 root root 643790848 11月 22 12:13 mysql-5.7.22-linux-glibc2.12-x86_64.tar.gz
-rw-r--r-- 1 root root     10645 11月 22 12:43 mysql.server
[root@itpux docker]# docker cp my.cnf 50d0fe24fdd050337276ec0611f0b72f81230ab2effa4f645e120ffa7f3b037b:/docker/mysql5.7/app/cnf
[root@itpux docker]# docker cp mysql.server 50d0fe24fdd050337276ec0611f0b72f81230ab2effa4f645e120ffa7f3b037b:/docker/mysql5.7/app/cnf
[root@itpux docker]# 

 

 

 

 

4.2 查看配置文件,  /mysql/app/mysql5.7

[root@dockermysql app]# pwd
/docker/mysql5.7/app
[root@dockermysql app]# ll
total 76
-rw-r--r-- 1 7161 31415 17987 Mar 4 2018 COPYING
-rw-r--r-- 1 7161 31415 2478 Mar 4 2018 README
drwxr-xr-x 2 root root 4096 Nov 22 01:15 bin
drwxr-xr-x 2 root root 4096 Nov 22 01:15 docs
drwxr-xr-x 3 root root 4096 Nov 22 01:15 include
drwxr-xr-x 5 root root 4096 Nov 22 01:15 lib
drwxr-xr-x 4 root root 4096 Nov 22 01:15 man
-rw-r--r-- 1 root root 11567 Nov 22 01:17 my.cnf
-rw-r--r-- 1 root root 10628 Nov 22 01:17 mysql.server
drwxr-xr-x 28 root root 4096 Nov 22 01:15 share
drwxr-xr-x 2 root root 4096 Nov 22 01:15 support-files
[root@dockermysql app]#

 4.1 上传配置文件

方法一:拷贝的方法,优势:原文件备份。
cp /docker/mysql5.7/app/cnf/mysql.server /mysql/app/mysql5.7/support-files/mysql.server cp /docker/mysql5.7/app/cnf/mysql.server /etc/init.d/mysqld.server cp /docker/mysql5.7/app/cnf/my.cnf /etc/my.cnf
方法二:链接方法,优势:只需要修改原文件,即自动同步。(建议)
ln -s /docker/mysql5.7/app/cnf/my.cnf /etc/my.cnf
ln -s /docker/mysql5.7/app/cnf/mysql.server /docker/mysql5.7/app/support-files/
ln -s /docker/mysql5.7/app/cnf/mysql.server /etc/init.d/mysqld.server
ln -s /docker/mysql5.7/app/cnf/mysql.server /etc/init.d/mysqld
ln -s /docker/mysql5.7/app/cnf/mysql.start /etc/init.d/mysql
chown -R mysql:mysql /docker/mysql5.7/*
chown -R mysql:mysql /etc/init.d/mysqld.server
chown -R mysql:mysql /etc/init.d/mysqld
chown -R mysql:mysql /etc/init.d/mysql  chown -R mysql:mysql /etc/my.cnf chmod -R 775 /docker/mysql5.7/

 

 

4.3  my.cnf配置文件

[mysqld]
#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
#新增#
sql_mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER"                #定义了你MySQL应该支持的sql语法,对数据的校验等等


##系统文件存储划分###
basedir=/docker/mysql5.7/app                                   #主程序安装地址
datadir=/docker/mysql5.7/data/3306/                                 #数据存放地址
pid-file=/docker/mysql5.7/data/3306/mysql.pid                        #进程pid地址
socket=/docker/mysql5.7/app/mysql.sock                       #sock文件地址
log_error=/docker/mysql5.7/log/3306/mysql-error.log             #log_error保存地址
plugin-dir=/docker/mysql5.7/app/lib/plugin                #innodb 添加 plugin_dir组件
#tmpdir= /mysql/data/tmp/   #此目录被 MySQL用来保存临时文件.例如,它被用来处理基于磁盘的大型排序,和内部排序一样,以及简单的临时表.如果你不创建非常大的临时文件,将其放置到 swapfs/tmpfs 文件系统上也许比较好。另一种选择是你也可以将其放置在独立的磁盘上.你可以使用”;”来放置多个路径,他们会按照 roud-robin 方法被轮询使用.
#slave-load-tmpdir= /usr/local/mysql/tmp/   #当 slave 执行 load data infile 时用
#风哥新增参数#
general_log_file=/docker/mysql5.7/log/3306/mysql-general.log                #general_log_file保存目录
slow_query_log_file=/docker/mysql5.7/log/3306/mysql-slow.log   #mysql慢查询日志保存地址


#####多实例管理##
server-id=3306                                      #用于复制环境钟标识实例,这个在复制环境里唯一,用于后期数据库多实例管理。
bind-address=0.0.0.0                             #绑定ip 这里表示绑定所有ip
user=mysql                                       #启动用户
port=3306                                          #端口
character-set-server=utf8                                    #服务端默认字符集,很重要,错误设置会出现乱码

#新增#
skip-character-set-client-handshake=1                #跳过mysql程序启动时的字符参数设置 ,使用服务器端字符集设置
autocommit=0                    #指事务非自动提交,自此句执行以后,每个SQL语句或者语句块所在的事务都需要显示"commit"才能提交事务。
#skip_name_resolve=1                #禁止域名解析的(当然,也包括主机名)


##数据连接参数配置##
#skip-grant-tables                                   #mysql数据库允许无密码登陆,最好删除不要。
max_connections=800                             #允许客户端并发连接的最大数量
max_connect_errors=1000                          #如果客户端尝试连接的错误数量超过这个参数设置的值,则服务器不再接受新的客户端连接。
#open_files_limit=65535                           #MySQL打开的文件描述符限制,默认最小1024;当open_files_limit没有被配置的时候,比较max_connections*5和ulimit-n的值,哪个大用哪个,当open_file_limit被配置的时候,比较open_files_limit和max_connections*5的值,哪个大用哪个
open-files-limit=65536                          ##增加每个进程的可打开文件数量.确认你已经将全系统限制设定的足够高!打开大量表需要将此值设大
table_open_cache=2000                             #所有线程能打开的表的数量
max_allowed_packet=16M                            #网络传输时单个数据包的大小。
binlog_cache_size=1M
key_buffer_size=32M                ## Key Buffer大小,用于缓存MyISAM表的索引块。决定数据库索引处理的速度(尤其是索引读)(1G 内存——>256M)
thread_cache_size=768                #每建立一个连接,都需要一个线程来与之匹配,此参数用来缓存空闲的线程,以至不被销毁,如果线程缓存中有空闲线程,这时候如果建立新连接,MYSQL就会很快的响应连接请求。


##查询缓存参数##
query_cache_type=1                #查询缓存功能的开启的关闭。
query_cache_size=1M             #用于查询缓存的内存大小。
query_cache_limit=2M            #示单个结果集所被允许缓存的最大值。风哥,无此参数。
ft_min_word_len=4
max_heap_table_size=8M
tmp_table_size=72M                ##临时表的最大大小,如果超过该值,则结果放到磁盘中,此限制是针对单个表的,而不是总和.
read_buffer_size=8M                ## 用于对MyISAM表全表扫描时使用的缓冲区大小。针对每个线程进行分配(前提是进行了全表扫描)
read_rnd_buffer_size=32M                ##MyISAM 以索引扫描(Random Scan)方式扫描数据的 buffer大小 
sort_buffer_size=32M                ##查询排序时所能使用的缓冲区大小。排序缓冲被用来处理类似 ORDER BY 以及 GROUP BY 队列所引起的排序.一个用来替代的基于磁盘的合并分类会被使用.查看 “Sort_merge_passes” 状态变量. 在排序发生时由每个线程分配 注意:该参数对应的分配内存是每连接独占!如果有 100 个连接,那么实际分配的总共排序缓冲区大小为 100 × 6 =600MB,所以,对于内存在 4GB 左右的服务器推荐设置为 6-8M。 
join_buffer_size=128M                ##联合查询操作所能使用的缓冲区大小,和 sort_buffer_size 一样,该参数对应的分配内存也是每连接独享!此缓冲被使用来优化全联合(full JOINs 不带索引的联合).类似的联合在极大多数情况下有非常糟糕的性能表现, 但是将此值设大能够减轻性能影响.通过 “Select_full_join”状态变量查看全联合的数量, 当全联合发生时,在每个线程中分配。




##log文件和error日志管理###
log_bin=mysql-bin        #风哥设置成"/log/bin_log/binlog"。
binlog_format=mixed
slow_query_log=1    #风哥为ON值。
expire_logs_days=90  #日志保存时间
long_query_time=10     #long_query_time查询等待秒数

performance_schema=0
explicit_defaults_for_timestamp=1                #一行数据中某些列被更新了,如果这一行中有timestamp类型的列,那么么这个timestamp列的数据也会被自动更新到
#lower_case_table_names=1
skip-external-locking

bulk_insert_buffer_size=8M
myisam_max_sort_file_size=10G                # # mysql重建索引时允许使用的临时文件最大大小
myisam_repair_threads=1
interactive_timeout=1800                #服务器关闭交互式连接前等待活动的秒数。交互式客户端定义为在mysql_real_connect()中使用CLIENT_INTERACTIVE选项的客户端。
wait_timeout=1800                #指的是mysql在关闭一个非交互的连接之前所要等待的秒数,其取值范围为1-2147483(Windows),1-31536000(linux),默认值28800。
#default-storage-engine=MyISAM
myisam_sort_buffer_size=135M                #最智

########风哥新增log settings########
log_output=FILE                #
general_log=0                #
log_queries_not_using_indexes=1                #
log_slow_admin_statements=1                #
log_slow_slave_statements=1                #
log_throttle_queries_not_using_indexes=10                #
min_examined_row_limit=100                #


########innodb settings########
# 根据您的服务器IOPS能力适当调整
# 一般配普通SSD盘的话,可以调整到 10000 - 20000
# 配置高端PCIe SSD卡的话,则可以调整的更高,比如 50000 - 80000
#skip-innodb  # 如果你的 MySQL 服务包含 InnoDB 支持但是并不打算使用的话,使用此选项会节省内存以及磁盘空间,并且加速某些部分
default_storage_engine=InnoDB        ##默认存储引擎
innodb_file_per_table=1                ## InnoDB为独立表空间模式,每个数据库的每个表都会生成一个数据空间
innodb_buffer_pool_size=500M                ##包括数据页、索引页、插入缓存、锁信息、自适应哈希所以、数据字典信息.InnoDB 使用一个缓冲池来保存索引和原始数据, 不像 MyISAM.这里你设置越大,你在存取表里面数据时所需要的磁盘 I/O 越少.在一个独立使用的数据库服务器上,你可以设置这个变量到服务器物理内存大小的 80%,不要设置过大,否则,由于物理内存的竞争可能导致操作系统的换页颠簸.注意在 32 位系统上你每个进程可能被限制在 2-3.5G 用户层面内存限制,所以不要设置的太高.
innodb_thread_concurrency=64        #风哥设置
innodb_purge_threads=4        #风哥设置
innodb_log_buffer_size=16M        #风哥设置
innodb_log_file_size=200M            #风哥设置成200M
innodb_log_files_in_group=2            #风哥设置    
innodb_max_dirty_pages_pct=90
innodb_lock_wait_timeout=5  #风哥设置
innodb_open_files=65536                ## 限制Innodb能打开的表的数据,如果库里的表特别多的情况,请增加这个。这个值默认是300
innodb_write_io_threads=4
innodb_read_io_threads=4
innodb_flush_log_at_trx_commit=1  #风哥设置

#-风哥新增innodb参数-#
innodb_io_capacity=4000                #
innodb_io_capacity_max=8000                #
innodb_buffer_pool_instances=8                #
innodb_buffer_pool_load_at_startup=1                #
innodb_buffer_pool_dump_at_shutdown=1                #
innodb_lru_scan_depth=2000                #
#innodb_flush_method=O_DIRECT                #
innodb_undo_logs=128                #
innodb_undo_tablespaces=3                #
innodb_undo_log_truncate=1                #
innodb_max_undo_log_size=2G                #
innodb_flush_neighbors=1                #
innodb_large_prefix=1                #
innodb_print_all_deadlocks=1                #
innodb_strict_mode=1                #
innodb_sort_buffer_size=64M                #
innodb_autoextend_increment=64                #
innodb_concurrency_tickets=5000                #
innodb_old_blocks_time=1000                #
innodb_stats_on_metadata=0                #
innodb_checksum_algorithm=0                #
innodb_data_file_path=ibdata1:200M;ibdata2:200M;ibdata3:200M:autoextend:max:5G                #
innodb_temp_data_file_path=ibtmp1:200M:autoextend:max:20G                #
innodb_buffer_pool_dump_pct=40                #
innodb_page_cleaners=4                #
innodb_purge_rseg_truncate_frequency=128                #

binlog_gtid_simple_recovery=1                #是合理的设置,BINLOG扫描非常的快因为只是第一个和最后一个BINLOG文件而已。
log_timestamps=system                #
#transaction_write_set_extraction=MURMUR32                #
show_compatibility_56=on                #


#-风哥新增参数-#
#transaction_isolation=READ-COMMITTED                #设定默认的事务隔离级别.可用的级别如下:READ-UNCOMMITTED, READ-COMMITTED, REPEATABLE-READ,SERIALIZABLE 1.READ UNCOMMITTED-读未提交 2.READ COMMITTE-读已提交 3.REPEATABLE READ -可重复读 4.SERIALIZABLE -串行
back_log=1024                ##接受队列,对于没建立 tcp 连接的请求队列放入缓存中,队列大小为 back_log,受限制与 OS 参数,试图设定 back_log 高于你的操作系统的限制将是无效的。默认值为 50。对于 Linux 系统推荐设置为小于512的整数。如果系统在一个短时间内有很多连接,则需要增大该参数的值
#flush_time=0                #
table_definition_cache=1400                #
#binlog_row_event_max_size=8K                #
#sync_master_info=10000                #
#sync_relay_log=10000                #
#sync_relay_log_info=10000                #


########replication settings########
#master_info_repository=TABLE                #
#relay_log_info_repository=TABLE                #
#log_bin=bin.log                #
#sync_binlog=1                #
#gtid_mode=on                #
#enforce_gtid_consistency=1                #
#log_slave_updates                #
#binlog_format=row                 #
#relay_log=relay.log                #
#relay_log_recovery=1                #
#slave_skip_errors=ddl_exist_errors                #定义复制过程中从服务器可以自动跳过的错误号,当复制过程中遇到定义的错误号,就可以自动跳过,直接执行后面的SQL语句。默认情况下该参数值是off



[client]
port=3306
socket=/docker/mysql5.7/app/mysql.sock

[mysql]
socket=/docker/mysql5.7/app/mysql.sock
no-beep   #关闭滴滴的声音
#风哥新增#
prompt="\\r:\\m:\\s> "                #
#no-auto-rehash                #
auto-rehash                  #允许通过 TAB 键提示
default-character-set=utf8  #数据库字符集

 

4.4 mysql.server配置文件

#!/bin/sh
# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB
# This file is public domain and comes with NO WARRANTY of any kind

# MySQL daemon start/stop script.

# Usually this is put in /etc/init.d (at least on machines SYSV R4 based
# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.
# When this is done the mysql server will be started when the machine is
# started and shut down when the systems goes down.

# Comments to support chkconfig on RedHat Linux
# chkconfig: 2345 64 36
# description: A very fast and reliable SQL database engine.

# Comments to support LSB init script conventions
### BEGIN INIT INFO
# Provides: mysql
# Required-Start: $local_fs $network $remote_fs
# Should-Start: ypbind nscd ldap ntpd xntpd
# Required-Stop: $local_fs $network $remote_fs
# Default-Start:  2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: start and stop MySQL
# Description: MySQL is a very fast and reliable SQL database engine.
### END INIT INFO
 
# If you install MySQL on some other places than /usr/local/mysql, then you
# have to do one of the following things for this script to work:
#
# - Run this script from within the MySQL installation directory
# - Create a /etc/my.cnf file with the following information:
#   [mysqld]
#   basedir=<path-to-mysql-installation-directory>
# - Add the above to any other configuration file (for example ~/.my.ini)
#   and copy my_print_defaults to /usr/bin
# - Add the path to the mysql-installation-directory to the basedir variable
#   below.
#
# If you want to affect other MySQL variables, you should make your changes
# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.

# If you change base dir, you must also change datadir. These may get
# overwritten by settings in the MySQL configuration files.

basedir=/docker/mysql5.7/app
datadir=/docker/mysql5.7/data/3306/

# Default value, in seconds, afterwhich the script should timeout waiting
# for server start. 
# Value here is overriden by value in my.cnf. 
# 0 means don't wait at all
# Negative numbers mean to wait indefinitely
service_startup_timeout=900

# Lock directory for RedHat / SuSE.
lockdir='/var/lock/subsys'
lock_file_path="$lockdir/mysql"

# The following variables are only set for letting mysql.server find things.

# Set some defaults
mysqld_pid_file_path=
if test -z "$basedir"
then
  basedir=/docker/mysql5.7/app
  bindir=/docker/mysql5.7/app/bin
  if test -z "$datadir"
  then
    datadir=/docker/mysql5.7/data/3306/
  fi
  sbindir=/docker/mysql5.7/app/bin
  libexecdir=/docker/mysql5.7/app/bin
else
  bindir="$basedir/bin"
  if test -z "$datadir"
  then
    datadir="$basedir/data"
  fi
  sbindir="$basedir/sbin"
  libexecdir="$basedir/libexec"
fi

# datadir_set is used to determine if datadir was set (and so should be
# *not* set inside of the --basedir= handler.)
datadir_set=

#
# Use LSB init script functions for printing messages, if possible
#
lsb_functions="/lib/lsb/init-functions"
if test -f $lsb_functions ; then
  . $lsb_functions
else
  log_success_msg()
  {
    echo " SUCCESS! $@"
  }
  log_failure_msg()
  {
    echo " ERROR! $@"
  }
fi

PATH="/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin"
export PATH

mode=$1    # start or stop

[ $# -ge 1 ] && shift


other_args="$*"   # uncommon, but needed when called from an RPM upgrade action
           # Expected: "--skip-networking --skip-grant-tables"
           # They are not checked here, intentionally, as it is the resposibility
           # of the "spec" file author to give correct arguments only.

case `echo "testing\c"`,`echo -n testing` in
    *c*,-n*) echo_n=   echo_c=     ;;
    *c*,*)   echo_n=-n echo_c=     ;;
    *)       echo_n=   echo_c='\c' ;;
esac

parse_server_arguments() {
  for arg do
    case "$arg" in
      --basedir=*)  basedir=`echo "$arg" | sed -e 's/^[^=]*=//'`
                    bindir="$basedir/bin"
            if test -z "$datadir_set"; then
              datadir="$basedir/data"
            fi
            sbindir="$basedir/sbin"
            libexecdir="$basedir/libexec"
        ;;
      --datadir=*)  datadir=`echo "$arg" | sed -e 's/^[^=]*=//'`
            datadir_set=1
    ;;
      --pid-file=*) mysqld_pid_file_path=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
      --service-startup-timeout=*) service_startup_timeout=`echo "$arg" | sed -e 's/^[^=]*=//'` ;;
    esac
  done
}

wait_for_pid () {
  verb="$1"           # created | removed
  pid="$2"            # process ID of the program operating on the pid-file
  pid_file_path="$3" # path to the PID file.

  i=0
  avoid_race_condition="by checking again"

  while test $i -ne $service_startup_timeout ; do

    case "$verb" in
      'created')
        # wait for a PID-file to pop into existence.
        test -s "$pid_file_path" && i='' && break
        ;;
      'removed')
        # wait for this PID-file to disappear
        test ! -s "$pid_file_path" && i='' && break
        ;;
      *)
        echo "wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path"
        exit 1
        ;;
    esac

    # if server isn't running, then pid-file will never be updated
    if test -n "$pid"; then
      if kill -0 "$pid" 2>/dev/null; then
        :  # the server still runs
      else
        # The server may have exited between the last pid-file check and now.  
        if test -n "$avoid_race_condition"; then
          avoid_race_condition=""
          continue  # Check again.
        fi

        # there's nothing that will affect the file.
        log_failure_msg "The server quit without updating PID file ($pid_file_path)."
        return 1  # not waiting any more.
      fi
    fi

    echo $echo_n ".$echo_c"
    i=`expr $i + 1`
    sleep 1

  done

  if test -z "$i" ; then
    log_success_msg
    return 0
  else
    log_failure_msg
    return 1
  fi
}

# Get arguments from the my.cnf file,
# the only group, which is read from now on is [mysqld]
if test -x "$bindir/my_print_defaults";  then
  print_defaults="$bindir/my_print_defaults"
else
  # Try to find basedir in /etc/my.cnf
  conf=/etc/my.cnf
  print_defaults=
  if test -r $conf
  then
    subpat='^[^=]*basedir[^=]*=\(.*\)$'
    dirs=`sed -e "/$subpat/!d" -e 's//\1/' $conf`
    for d in $dirs
    do
      d=`echo $d | sed -e 's/[     ]//g'`
      if test -x "$d/bin/my_print_defaults"
      then
        print_defaults="$d/bin/my_print_defaults"
        break
      fi
    done
  fi

  # Hope it's in the PATH ... but I doubt it
  test -z "$print_defaults" && print_defaults="my_print_defaults"
fi

#
# Read defaults file from 'basedir'.   If there is no defaults file there
# check if it's in the old (depricated) place (datadir) and read it from there
#

extra_args=""
if test -r "$basedir/my.cnf"
then
  extra_args="-e $basedir/my.cnf"
fi

parse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`

#
# Set pid file if not given
#
if test -z "$mysqld_pid_file_path"
then
  mysqld_pid_file_path=$datadir/`hostname`.pid
else
  case "$mysqld_pid_file_path" in
    /* ) ;;
    * )  mysqld_pid_file_path="$datadir/$mysqld_pid_file_path" ;;
  esac
fi

case "$mode" in
  'start')
    # Start daemon

    # Safeguard (relative paths, core dumps..)
    cd $basedir

    echo $echo_n "Starting MySQL"
    if test -x $bindir/mysqld_safe
    then
      # Give extra arguments to mysqld with the my.cnf file. This script
      # may be overwritten at next upgrade.
      $bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" $other_args >/dev/null &
      wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

      # Make lock for RedHat / SuSE
      if test -w "$lockdir"
      then
        touch "$lock_file_path"
      fi

      exit $return_value
    else
      log_failure_msg "Couldn't find MySQL server ($bindir/mysqld_safe)"
    fi
    ;;

  'stop')
    # Stop daemon. We use a signal here to avoid having to know the
    # root password.

    if test -s "$mysqld_pid_file_path"
    then
      # signal mysqld_safe that it needs to stop
      touch "$mysqld_pid_file_path.shutdown"

      mysqld_pid=`cat "$mysqld_pid_file_path"`

      if (kill -0 $mysqld_pid 2>/dev/null)
      then
        echo $echo_n "Shutting down MySQL"
        kill $mysqld_pid
        # mysqld should remove the pid file when it exits, so wait for it.
        wait_for_pid removed "$mysqld_pid" "$mysqld_pid_file_path"; return_value=$?
      else
        log_failure_msg "MySQL server process #$mysqld_pid is not running!"
        rm "$mysqld_pid_file_path"
      fi

      # Delete lock for RedHat / SuSE
      if test -f "$lock_file_path"
      then
        rm -f "$lock_file_path"
      fi
      exit $return_value
    else
      log_failure_msg "MySQL server PID file could not be found!"
    fi
    ;;

  'restart')
    # Stop the service and regardless of whether it was
    # running or not, start it again.
    if $0 stop  $other_args; then
      $0 start $other_args
    else
      log_failure_msg "Failed to stop running server, so refusing to try to start."
      exit 1
    fi
    ;;

  'reload'|'force-reload')
    if test -s "$mysqld_pid_file_path" ; then
      read mysqld_pid <  "$mysqld_pid_file_path"
      kill -HUP $mysqld_pid && log_success_msg "Reloading service MySQL"
      touch "$mysqld_pid_file_path"
    else
      log_failure_msg "MySQL PID file could not be found!"
      exit 1
    fi
    ;;
  'status')
    # First, check to see if pid file exists
    if test -s "$mysqld_pid_file_path" ; then 
      read mysqld_pid < "$mysqld_pid_file_path"
      if kill -0 $mysqld_pid 2>/dev/null ; then 
        log_success_msg "MySQL running ($mysqld_pid)"
        exit 0
      else
        log_failure_msg "MySQL is not running, but PID file exists"
        exit 1
      fi
    else
      # Try to find appropriate mysqld process
      mysqld_pid=`pidof $libexecdir/mysqld`

      # test if multiple pids exist
      pid_count=`echo $mysqld_pid | wc -w`
      if test $pid_count -gt 1 ; then
        log_failure_msg "Multiple MySQL running but PID file could not be found ($mysqld_pid)"
        exit 5
      elif test -z $mysqld_pid ; then 
        if test -f "$lock_file_path" ; then 
          log_failure_msg "MySQL is not running, but lock file ($lock_file_path) exists"
          exit 2
        fi 
        log_failure_msg "MySQL is not running"
        exit 3
      else
        log_failure_msg "MySQL is running but PID file could not be found"
        exit 4
      fi
    fi
    ;;
    *)
      # usage
      basename=`basename "$0"`
      echo "Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]"
      exit 1
    ;;
esac

exit 0

 

五、数据库安装

 

5.1 初始化数据库

进入安装程序目录/docker/mysql5.7/app/bin/

./mysqld --initialize --user=mysql --basedir=/docker/mysql5.7/app/ --datadir=/docker/mysql5.7/data/3306/

问题1: 如果提示错误,无法执行,请见本页第6部分问题处理。

 

5.2  注意,需要进入/mysql/app/mysql5.7/support-files目录运行mysql.server,才能生成/mysql/app/mysql5.7里的mysql.sock和mysql.sock.lock文件

[root@dockermysql support-files]# ./mysql.server start
Starting MySQL... SUCCESS! 
[root@dockermysql support-files]# ./mysql.server stop 
Shutting down MySQL.. SUCCESS! 
[root@dockermysql support-files]# ./mysql.server start
Starting MySQL... SUCCESS!

  

5.3 到/mysql/log/3306,LOG日志中找密码,由上可知,初始化的root 密码

[root@dockermysql 3306]# pwd
/docker/mysql5.7/log/3306
[root@dockermysql 3306]# cat mysql-error.log 
 100 200
 100 200
 100 200
 100 200
 100 200
2018-11-22T01:58:01.234968-00:00 0 [Warning] InnoDB: New log files created, LSN=48434
 100 200
2018-11-22T01:58:02.462387-00:00 0 [Warning] InnoDB: Creating foreign key constraint system tables.
2018-11-22T01:58:02.520919-00:00 0 [Warning] No existing UUID has been found, so we assume that this is the first time that this server has been started. Generating a new UUID: 0b7decf5-edfa-11e8-b456-0242ac110002.
2018-11-22T01:58:02.521609-00:00 0 [Warning] Gtid table is not ready to be used. Table 'mysql.gtid_executed' cannot be opened.
2018-11-22T01:58:02.522959-00:00 1 [Note] A temporary password is generated for root@localhost: vxwha?e9*rkH
[root@dockermysql 3306]# 

 

5.4   配置mysql开机启动

  详细配置方式,请见LINUX目录下的《linux chkconfig 管理服务开机自启动》

[root@dockermysql init.d]# chkconfig --add mysqld

 

[root@dockermysql init.d]# chmod 755 /etc/rc.d/init.d/mysqld
[root@dockermysql init.d]# chkconfig

Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

mysqld             0:off    1:off    2:on    3:on    4:on    5:on    6:off
[root@dockermysql init.d]# pwd
/etc/rc.d/init.d

 

 5.5 修改容器的时间同步

[root@itpux Asia]# docker cp  /usr/share/zoneinfo/Asia/Shanghai 7a22819c479c:/etc/localtime

 修改前:

root@dockermysql:/# date
Wed Nov 21 11:13:33 UTC 2018

 修改后:

root@dockermysql:/etc# date
Wed Nov 21 19:19:57 CST 2018

 

 

5.5 连接数据库 更新初始密码
----登陆Mysql失败,使用初始密码登陆

创建用户、刷新权限与分配权限

mysql -uroot -p

SET PASSWORD=PASSWORD('root');
CREATE USER 'itpux'@'%' IDENTIFIED BY 'itpux';
FLUSH PRIVILEGES;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'itpux'@'%' IDENTIFIED BY 'itpux' WITH GRANT OPTION;

 

--如果临时密码失效,请修改my.cnf参数,为免密码登陆,并重启MYSQL服务
--修改my.cnf参数,为需密码登陆,并重启MYSQL服务


-----登陆到数据库创建示例数据库\显示所有数据库\查询系统有哪 些用户

use mysql;
show databases;
SELECT HOST,USER FROM mysql.user;

 

-----创建一个数据库

CREATE DATABASE itpux;
use itpux;

 

-----创建表和数据插入

CREATE TABLE dept(
deptno INT AUTO_INCREMENT PRIMARY KEY,
dname VARCHAR(15),
loc VARCHAR(50)
)ENGINE=INNOBASE;

INSERT INTO dept(dname,loc) VALUE('it','bj'),('cw','sh'),('hr','sz');
COMMIT;

 

 

5.6  查看创建后的容器大小

[root@dockermysql support-files]# df -h
Filesystem                                                                                       Size  Used Avail Use% Mounted on
/dev/mapper/docker-8:1-2229670-d2e2f205de6b0f5e560d247ac7ae9952a471aa703d8bb2357e113b1adcb93a85   10G  4.0G  6.1G  40% /
tmpfs                                                                                            911M     0  911M   0% /dev
tmpfs                                                                                            911M     0  911M   0% /sys/fs/cgroup
/dev/sda1                                                                                         46G   11G   32G  26% /etc/hosts
shm                                                                                               64M     0   64M   0% /dev/shm
[root@dockermysql support-files]# 

 

 

六、相关问题处理

6.1 如果提示如下问题,需先安装numactl.x86_64安装

[root@44de31e1948f bin]# ./mysqld --initialize --user=mysql --basedir=/mysql/app/mysql5.7 --datadir=/mysql/data/3306/data
./mysqld: error while loading shared libraries: libnuma.so.1: cannot open shared object file: No such file or directory

 

https://blog.csdn.net/m0_37886429/article/details/78844358?utm_source=blogxgwz5

A、如果已经安装了libnuma.so.1,先yum remove libnuma.so.1

B、安装libaio

[root@dockermysql bin]# rpm -qa|grep libaio 
[root@dockermysql bin]# yum install  libaio-devel.x86_64

 

C、yum -y install numactl.x86_64

root@44de31e1948f bin]# yum install numactl.x86_64
Loaded plugins: fastestmirror, ovl
Loading mirror speeds from cached hostfile
 * base: mirrors.aliyun.com
 * extras: mirrors.aliyun.com
 * updates: mirror.lzu.edu.cn
Resolving Dependencies
--> Running transaction check
---> Package numactl.x86_64 0:2.0.9-7.el7 will be installed
--> Processing Dependency: libnuma.so.1(libnuma_1.4)(64bit) for package: numactl-2.0.9-7.el7.x86_64
--> Processing Dependency: libnuma.so.1(libnuma_1.3)(64bit) for package: numactl-2.0.9-7.el7.x86_64
--> Processing Dependency: libnuma.so.1(libnuma_1.2)(64bit) for package: numactl-2.0.9-7.el7.x86_64
--> Processing Dependency: libnuma.so.1(libnuma_1.1)(64bit) for package: numactl-2.0.9-7.el7.x86_64
--> Processing Dependency: libnuma.so.1()(64bit) for package: numactl-2.0.9-7.el7.x86_64
--> Running transaction check
---> Package numactl-libs.x86_64 0:2.0.9-7.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===============================================================================================================================================================================================
 Package                                          Arch                                       Version                                            Repository                                Size
===============================================================================================================================================================================================
Installing:
 numactl                                          x86_64                                     2.0.9-7.el7                                        base                                      66 k
Installing for dependencies:
 numactl-libs                                     x86_64                                     2.0.9-7.el7                                        base                                      29 k

Transaction Summary
===============================================================================================================================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 95 k
Installed size: 191 k
Is this ok [y/d/N]: y
Downloading packages:
(1/2): numactl-libs-2.0.9-7.el7.x86_64.rpm                                                                                                                              |  29 kB  00:00:00     
(2/2): numactl-2.0.9-7.el7.x86_64.rpm                                                                                                                                   |  66 kB  00:00:00     
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                                                                          322 kB/s |  95 kB  00:00:00     
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : numactl-libs-2.0.9-7.el7.x86_64                                                                                                                                             1/2 
  Installing : numactl-2.0.9-7.el7.x86_64                                                                                                                                                  2/2 
  Verifying  : numactl-libs-2.0.9-7.el7.x86_64                                                                                                                                             1/2 
  Verifying  : numactl-2.0.9-7.el7.x86_64                                                                                                                                                  2/2 

Installed:
  numactl.x86_64 0:2.0.9-7.el7                                                                                                                                                                 

Dependency Installed:
  numactl-libs.x86_64 0:2.0.9-7.el7                                                                                                                                                            

Complete!
[root@44de31e1948f bin]# 

 

6.2 问题2:如果提示如下,请将/docker/mysql5.7/data/3306/下,所有文件删除。

[root@dockermysql bin]# ./mysqld --initialize --user=mysql --basedir=/docker/mysql5.7/app/ --datadir=/docker/mysql5.7/data/3306/
2018-11-22T01:54:58.264105-00:00 0 [ERROR] --initialize specified but the data directory has files in it. Aborting.
2018-11-22T01:54:58.264216-00:00 0 [ERROR] Aborting

 

6.3 问题3:输入mysql -uroot -p后报错,无此命令。

[root@dockermysql 3306]# mysql -u root -p
bash: mysql: command not found

 

[root@44de31e1948f mysql5.7]# ln -s /docker/mysql5.7/app/bin/mysql /usr/bin
[root@44de31e1948f mysql5.7]# mysql -uroot -p
Enter password:

 

参考:https://www.cnblogs.com/jr1260/p/6590860.html

  6.4 问题4:无法执行 service mysqld stop等

service mysqld stop 无法执行
service mysqld start  无法执行


[root@dockermysql init.d]# service mysqld start
bash: service: command not found

 

6.4.1 安装 initscripts

[root@dockermysql init.d]# c
initscripts.x86_64                        9.49.41-1.el7_5.2              updates
[root@dockermysql init.d]# yum install initscripts

  

七、创建镜像

 

[root@itpux docker]# docker ps -a
CONTAINER ID        IMAGE                     COMMAND                  CREATED             STATUS                        PORTS               NAMES
50d0fe24fdd0        docker.io/centos:latest   "/bin/bash"              About an hour ago   Exited (137) 47 seconds ago                       mysqldb
582f20247efe        docker.io/nginx:latest    "nginx -g 'daemon ..."   15 hours ago        Exited (0) 15 hours ago                           nginx
[root@itpux docker]# docker commit -m "mysql5.7" 50d0fe24fdd0 centos/mysql5.7:v6
sha256:35dee3f4071b9b6273ffdfcb0282a3d25e3fe911e41900da1b7050f29418ac00
[root@itpux docker]# docker images
REPOSITORY           TAG                 IMAGE ID            CREATED             SIZE
centos/mysql5.7      v6                  35dee3f4071b        8 seconds ago       4.28 GB

 

 

 

八、镜像安装前,需要将原容器删除,并参照后续“容器中安装镜像二进制mysql”章节。

 

posted on 2018-11-20 20:43  luoxf  阅读(906)  评论(0)    收藏  举报

导航