基于Dockerfile方式创建MariaDB镜像

1 设置创建目录和文件

[root@test01 ~]# mkdir mariadb_dockerfile && cd mariadb_dockerfile
[root@test01 mariadb_dockerfile]# touch db_init.sh 
[root@test01 mariadb_dockerfile]# touch run.sh

2 编辑Dockerfile等文件

Dockerfile
[root@test01 mariadb_dockerfile]# cat Dockerfile 
#使用的基础镜像
FROM centos:7.4.1708

#添加作者信息
MAINTAINER liuxin 842887233@qq.com

#安装mariadb数据库
RUN yum -y install mariadb-server

#设置环境变量,便于管理
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
RUN /root/db_init.sh

#导出端口
EXPOSE 3306

#添加启动文件
ADD run.sh /root/run.sh
RUN chmod 775 /root/run.sh

#设置默认启动命令
CMD ["/root/run.sh"]
db_init.sh
[root@test01 mariadb_dockerfile]# cat db_init.sh 
#!/bin/bash

mysql_install_db --user=mysql
sleep 3
mysqld_safe &
sleep 3
#mysqladmin -u "$MARIADB_USER" password "$MARIADB_PASS"
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;"
run.sh
[root@test01 mariadb_dockerfile]# cat run.sh 
#!/bin/bash
mysqld_safe

3  创建镜像
[root@test01 mariadb_dockerfile]# docker build -t liuxin/centos-mariadb:v1 ./
4 创建容器
[root@test01 mariadb_dockerfile]# docker run -d -p 13306:3306 liuxin/centos-mariadb:v1 /root/run.sh
[root@test01 mariadb_dockerfile]# docker ps
CONTAINER ID        IMAGE                      COMMAND             CREATED             STATUS              PORTS                     NAMES
7743527ac603        liuxin/centos-mariadb:v1   "/root/run.sh"      5 seconds ago       Up 3 seconds        0.0.0.0:13306->3306/tcp   nostalgic_mirzakhani
5 验证登录
[root@test01 mariadb_dockerfile]# yum -y install mariadb

[root@master mariadb_dockerfile]# docker ps |grep liuxin/centos-mariadb:v1
efbd88a6d952        liuxin/centos-mariadb:v1               "/root/run.sh"           3 minutes ago       Up 3 minutes           0.0.0.0:13306->3306/tcp     optimistic_shaw

[root@test01 mariadb_dockerfile]#  docker inspect efbd88a6d952
**"IPAddress": "172.17.0.2",**
[root@test01 mariadb_dockerfile]# mysql -uroot -h 127.0.0.2 --port=13306 -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 1
Server version: 5.5.56-MariaDB MariaDB Server

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> exit

你可能感兴趣的:(Dockerfile,docker)