Dockfile目录如下:
/root/my-dockerfile/
├── db_init.sh
├── Dockerfile
└── run.sh
1.Dockefile文件如下:
FROM v10-sp1:v1
MAINTAINER hejing
RUN mkdir -p /var/run && touch /var/run/passwd && yum -y install mariadb mariadb-server hostname
ENV MARIADB_USER root
ENV MARIADB_PASS 123456
ENV LC_ALL en_US.UTF-8
ADD db_init.sh /etc/init.d/db_init.sh
RUN chmod 775 /etc/init.d/db_init.sh && /etc/init.d/db_init.sh
ADD run.sh /etc/init.d/run.sh
RUN chmod 755 /etc/init.d/run.sh
EXPOSE 3306
CMD ["/etc/init.d/run.sh"]
2.数据库初始化脚本
#!/bin/bash
#Author:hejing
#Date:2021-11-13
#Function:数据库初始化脚本及配置
function db_init {
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;"
}
db_init
3.CMD命令脚本
#!/bin/bash
mysqld_safe
4.执行
[root@v10-sp2-0524-21 my-dockerfile]# docker build -t v10-sp1-mariadb:v1 .
Sending build context to Docker daemon 4.096kB
Step 1/12 : FROM v10-sp1:v1
---> 9616a8563d77
Step 2/12 : MAINTAINER hejing
---> Running in 23a710c1a1f1
...
...
Step 12/12 : CMD ["/etc/init.d/run.sh"]
---> Running in 31e9b0d7a777
Removing intermediate container 31e9b0d7a777
---> 0ab07801cc61
Successfully built 0ab07801cc61
Successfully tagged v10-sp1-mariadb:v1
[root@v10-sp2-0524-21 my-dockerfile]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
v10-sp1-mariadb v1 0ab07801cc61 About a minute ago 1.26GB
v10-sp1 v1 9616a8563d77 5 hours ago 954MB
[root@v10-sp2-0524-21 my-dockerfile]# docker run -itd -p33060:3306 --name=my-mariadb v10-sp1-mariadb:v1
0d91ed218f863959cc5fdc73c0c8f121ade4c8cbf300560fac4487acbb424ea7
[root@v10-sp2-0524-21 my-dockerfile]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
0d91ed218f86 v10-sp1-mariadb:v1 "/etc/init.d/run.sh" 12 seconds ago Up 12 seconds 0.0.0.0:33060->3306/tcp my-mariadb
[root@v10-sp2-0524-21 my-dockerfile]# docker inspect 0d | grep -i ipaddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.2",
"IPAddress": "172.17.0.2",
[root@v10-sp2-0524-21 my-dockerfile]# mysql -uroot -p123456 -h172.17.0.2
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.5.5-10.3.9-MariaDB MariaDB Server
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select version();
+----------------+
| version() |
+----------------+
| 10.3.9-MariaDB |
+----------------+
1 row in set (0.00 sec)
mysql>
案例仅供测试学习,切莫用在生产!!!