docker 自动化部署mysql

docker 自动化部署mysql


#!/bin/bash
#当前路径
cur_dir=$(cd "$(dirname "$0")"; pwd)
cd $cur_dir
#后出现的代码,一旦出现了返回值非零,整个脚本就会立即退出
#set -e
#redis镜像名称
IMAGE_NAME=mysql:latest
#容器名称
CONTAINER_NAME=mysql_docker001
#容器ip
#CONTAINER_IP=''
# 登录密码
MYSQL_PASSWORD="123456"
# 宿主机映射端口
MAP_PORT=3306
IP=`ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|grep broadcast|awk '{print $2}'|tr -d "addr:"​`
#日志文件连接 %T - 24小时制 %X 日期
LOG_FILE=$cur_dir/${0}.`date +%Y%m%d%H%M%S`.log
#脚本文件
SRCIPT_NAME='temp_mysql.sh'
SRCIPT_FILE=$cur_dir/${SRCIPT_NAME}
echo $LOG_FILE | tee -a $LOG_FILE
#echo $SRCIPT_FILE | tee -a $LOG_FILE

#创建mysql容器
create_mysql(){
	#拉取redis镜像
	docker pull $IMAGE_NAME  | tee -a $LOG_FILE
	#停止及删除redis容器
	docker stop `docker ps | grep ${CONTAINER_NAME} | awk '{print $1}'`  > /dev/null 2>&1 | echo
	docker rm `docker ps -a| grep ${CONTAINER_NAME} | awk '{print $1}'`   > /dev/null 2>&1 | echo
	#创建mysql容器
	docker run -dit --name ${CONTAINER_NAME} -p ${MAP_PORT}:3306 -e MYSQL_ROOT_PASSWORD=${MYSQL_PASSWORD} ${IMAGE_NAME}  | tee -a $LOG_FILE  
	return 0
}

#生成脚本
create_script(){
	#CONTAINER_IP=`docker inspect mysql_docker001| grep  IPAddress | grep -v null |head -1 | awk -F '"' '{print $4}'`
	echo '#!/bin/bash' > ${SRCIPT_FILE}
	echo "mysql  -uroot -p${MYSQL_PASSWORD} -e \"GRANT ALL ON *.* TO 'root'@'%'; ALTER USER 'root'@'localhost' IDENTIFIED BY '${MYSQL_PASSWORD}' PASSWORD EXPIRE NEVER; ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '${MYSQL_PASSWORD}'; flush privileges;\" "   >> ${SRCIPT_FILE}
}

#配置mysql数据库
config_database(){
	create_script
	docker cp ${SRCIPT_FILE} ${CONTAINER_NAME}:/ | tee -a $LOG_FILE
	docker exec -it ${CONTAINER_NAME} /bin/bash -c "  chmod +x /${SRCIPT_NAME}; /${SRCIPT_NAME};  " | tee -a $LOG_FILE
	echo Enforcing MySQL ERROR 2002:
	echo Please execute the following command many times:
	echo ====================
	echo docker exec -it ${CONTAINER_NAME} /bin/bash -c " \"  chmod +x /${SRCIPT_NAME}; /${SRCIPT_NAME}; \"  "  
	echo ====================
}

#主函数
main(){	
	#创建mysql容器
	echo "doing create mysql container"
	create_mysql
	#配置mysql数据库
	echo "doing set mysql container "
	config_database
	#echo "MySQL Deployment configuration successful :" 
	#echo 'IP' ${IP}  'PORT' ${MAP_PORT}
}


main $@

cd $cur_dir
exit $?

你可能感兴趣的:(Docker,docker,mysql,自动化)