在容器中部署MySQL需要注意的几个点

  • 一般MySQL在生产环境中不会部署在容器中,通常是在裸金属上部署的,因为MySQL要占用资源较多 很难部署多个。

容易出现的部署问题

  • 系统自带的my.conf属组和属主都是root,MySQL在启动过程中没有权限调用,需要使用chmod更改属主和属组。
  • 发现创建过程都正常,但是服务依旧没办法在启动后自动启动,解决方案为:将MySQL设为开机自启,最后的CMD使用一个没有实际意义的命令代替即可。

部署过程

关闭所有防火墙服务和策略
先将MySQL的编译安装包放入服务器中

mkdir mysql #创建dockerfile目录
cd mysql
vim Dockerfile
FROM centos:7
RUN yum -y install \
ncurses \
ncurses-devel \
bison \
cmake \
make \
gcc \
gcc-c++ #安装MySQL和编译所需的环境包
RUN useradd -s /sbin/nologin mysql
ADD mysql-boost-5.7.20.tar.gz /usr/local/src
WORKDIR /usr/local/src/mysql-5.7.20/
RUN cmake \
-DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
-DMYSQL_UNIX_ADDR=/usr/local/mysql/mysql.sock \
-DSYSCONFDIR=/etc \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_INNOBASE_STORAGE_ENGINE=1 \
-DWITH_ARCHIVE_STORAGE_ENGINE=1 \
-DWITH_BLACKHOLE_STORAGE_ENGINE=1 \
-DWITH_PERFSCHEMA_STORAGE_ENGINE=1 \
-DMYSQL_DATADIR=/usr/local/mysql/data \
-DWITH_BOOST=boost \
-DWITH_SYSTEMD=1 && make -j2 && make install #-j2 编译时 使用2个线程进行
RUN chown -R mysql:mysql /usr/local/mysql/
RUN rm -rf /etc/my.cnf #删除原本的自带MySQL配置文件
ADD my.cnf /etc
RUN chown mysql:mysql /etc/my.cnf #修改配置文件属主属组
ENV PATH=/usr/local/mysql/bin:/usr/local/mysql/lib:$PATH #配置环境变量
WORKDIR /usr/local/mysql/
RUN bin/mysqld \
--initialize-insecure \
--user=mysql \
--basedir=/usr/local/mysql \
--datadir=/usr/local/mysql/data #初始化
RUN cp /usr/local/mysql/usr/lib/systemd/system/mysqld.service /usr/lib/systemd/system/
EXPOSE 3306
RUN echo -e "#!/bin/sh \nsystemctl enable mysqld" > /run.sh #设置开机自启动
RUN chmod 755 /run.sh
RUN sh /run.sh
CMD ["init"]
保存退出
vi my.cnf #编辑MySQL配置文件
[client]
port = 3306
default-character-set=utf8
socket = /usr/local/mysql/mysql.sock

[mysql]
port = 3306
default-character-set=utf8
socket = /usr/local/mysql/mysql.sock

[mysqld]
user = mysql
basedir = /usr/local/mysql
datadir = /usr/local/mysql/data
port = 3306
character_set_server=utf8
pid-file = /usr/local/mysql/mysqld.pid
socket = /usr/local/mysql/mysql.sock
server-id = 1

sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_AUTO_VALUE_ON_ZERO,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,PIPES_AS_CONCAT,ANSI_QUOTES
保存退出
docker build -t mysql:new .
docker images
docker run --name=mysql_server -d -P --privileged mysql:new  #--privileged 不降权
docker ps -a
docker exec -it 799a7d726ab1 /bin/bash #进入容器
mysql -uroot -p
grant all privileges on *.* to 'root'@'%' identified by 'abc123'; #为宿主机授权
grant all privileges on *.* to 'root'@'localhost' identified by 'abc123'
exit
exit
yum -y install mysql
mysql -h 20.0.0.18 -u root -P 32780 -pabc123
MySQL [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.01 sec)

MySQL [(none)]> exit
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐