创建工作目录
[root@localhost ~]# mkdir mysql
[root@localhost ~]# cd mysql/
编写Dockerfile文件
[root@localhost mysql]# vim Dockerfile
FROM centos:7
MAINTAINER Crushlinux <crushlinux@163.com>
#安装mariadb数据库
RUN yum install -y mariadb mariadb-server mariadb-devel
#设置环境变量,便于管理
ENV MARIADB_USER root
ENV MARIADB_PASS 123456
#让容器支持中文
ENV LC_ALL en_US.UTF-8
#初始化数据库
ADD db_init.sh /root/db_init.sh
RUN chmod 775 /root/db_init.sh && /root/db_init.sh
#导出端口
EXPOSE 3306
#设置默认启动命令
CMD ["mysqld_safe"]
[root@localhost mysql]# vim db_init.sh
#!/bin/bash
mysql_install_db --user=mysql
sleep 3
mysqld_safe &
sleep 3
mysql -e "use mysql; grant all privileges on *.* to '$MARIADB_USER'@'%' identified by '$MARIADB_PASS' with grant option;"
h=$(hostname)
mysql -e "use mysql; update user set password=password('$MARIADB_PASS') where user='$MARIADB_USER' and host='$h';"
mysql -e "flush privileges;"
~
构建镜像
[root@localhost mysql]# docker build -t mysql:new .
[root@localhost mysql]# docker images mysql:new
REPOSITORY TAG IMAGE ID CREATED SIZE
mysql new 7e3136f324a6 41 seconds ago 1.02 GB
[root@localhost mysql]# docker run -d -p 3306:3306 --name=mysql mysql:new
6c1e44f274a40d5592ff144a3e0e5b6875dbaa9f08441c469d282db658c35944
测试容器
因为宿主机没有mariadb所以要下载
[root@localhost mysql]# yum -y install mariadb mariadb-devel
测试容器
[root@localhost mysql]# mysql -h 192.168.50.59 -u root -P 3306 -p123456
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 2
Server version: 5.5.68-MariaDB MariaDB Server
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> exit
Bye
成功