本文摘自:https://www.cnblogs.com/jsonhc/p/7807931.html
利用Dockerfile自定义构建MySQL服务折腾了几天,一直在启动服务上出现错误,现在终于解决了该问题,这里进行记录一下
本文参考http://iamdavidxie.com/2014/07/21/create-a-mariadb-service-on-centos-with-docker/
此次Dockerfile文件中以centos:latest为基础镜像,在此基础上进行安装MySQL服务(这里以mariadb为例)
查看整个构建目录:
[root@docker mysql]# tree
.
├── business.sql
├── Dockerfile
├── MariaDB-10.0.33-centos7-x86_64-client.rpm
├── MariaDB-10.0.33-centos7-x86_64-common.rpm
├── MariaDB-10.0.33-centos7-x86_64-compat.rpm
├── MariaDB-10.0.33-centos7-x86_64-server.rpm
├── mariadb.repo
├── server.cnf
├── setup.sh
└── setup.sh.bak
目录中有下载好的mariadb安装的包,当然如果你网络好,只需要配置repo就行,然后将Dockerfile中的安装rpm的过程换成替换repo就ok
下面介绍Dockerfile文件,并介绍构建过程执行了什么:
[root@docker mysql]# cat Dockerfile
FROM centos
MAINTAINER json_hc@163.com
COPY MariaDB-10.0.33-centos7-x86_64-client.rpm /root/MariaDB-10.0.33-centos7-x86_64-client.rpm
COPY MariaDB-10.0.33-centos7-x86_64-common.rpm /root/MariaDB-10.0.33-centos7-x86_64-common.rpm
COPY MariaDB-10.0.33-centos7-x86_64-compat.rpm /root/MariaDB-10.0.33-centos7-x86_64-compat.rpm
COPY MariaDB-10.0.33-centos7-x86_64-server.rpm /root/MariaDB-10.0.33-centos7-x86_64-server.rpm
WORKDIR /root
RUN yum remove mysql-libs -y
RUN yum -y install *.rpm
ADD business.sql /root/business.sql
ADD server.cnf /etc/my.cnf.d/server.cnf
ADD setup.sh /root/setup.sh
RUN yum clean all
RUN chmod +x /root/setup.sh
EXPOSE 3306
CMD ["/root/setup.sh"]
1、构建使用的基础镜像为centos:latest
2、将下载好的rpm包copy到镜像中,然后进行安装
3、将需要执行的sql、配置文件,最后执行的shell脚本也copy到镜像中
在执行setup.sh
脚本之前mariadb
服务已经安装完毕,基本的数据目录还是/var/lib/mysql
将配置文件拷贝到了镜像中,查看配置文件:
[root@docker mysql]# cat server.cnf
[mysqld]
bind-address=0.0.0.0
console=1
general_log=1
general_log_file=/dev/stdout
#log_error=/dev/stderr
collation-server=utf8_unicode_ci
character-set-server=utf8
里面的内容可以进行修改或者添加更多
查看setup.sh的内容:
[root@docker mysql]# cat setup.sh
#!/bin/sh
chown -R mysql:mysql /var/lib/mysql
mysql_install_db --user=mysql > /dev/null
mysqld_safe --user=mysql &
sleep 5
mysql < /root/business.sql
sleep 5
ps -wef | grep mysql | grep -v grep | awk '{print $2}' | xargs kill -9
mysqld_safe --user=mysql
由于需要重新将安装好的mariadb服务进行初始化,所以避免出错可以将数据目录进行权限授予
MySQL5.6的初始化为mysql_install_db
加上一些参数
初始化数据库后,后台开启mariadb
服务,然后将sql进行执行:
[root@docker mysql]# cat business.sql
create database wordpress DEFAULT CHARACTER SET utf8;
USE mysql;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
UPDATE user SET password=PASSWORD("root") WHERE user='root';
FLUSH PRIVILEGES;
sql内容就是创建的库和设置root账号的密码
sql执行完成后setup.sh脚本后面就是将mariadb进程杀掉,最后由前台运行mariadb服务,如果在启动容器中遇见了错误,请利用docker logs container_name/container_id
进行查看,根据错误提示进行解决
自定义构建MySQL服务的项目可以在github查看:https://github.com/jsonhc/docker_project/tree/master/docker_dockerfile/lnmp/mysql
“The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time.” – Tom Cargill
标 题:Dockerfile构建MySQL