Docker Hub中有很多好用的Docker镜像,但镜像到底如何工作、能做什么、怎么做值得我们研究,如下所示为MySQL官方镜像的docker-entrypoint.sh脚本分析:
#!/bin/bash
set -eo pipefail
shopt -s nullglob
################################################################
# 若启动命令时附加了参数,则在参数前添加mysqld,如$0 -f test,则经过此代码处理后,
# $@参数变mysqld -f test。其中${1:0:1}从$1参数第0个位置取1字符,如$1为-f,则
# 取'-'字符,若条件为真,通过set命令重置$@参数,添加mysqld前缀,即经过处理后$1变
# 为mysqld。
################################################################
# if command starts with an option, prepend mysqld
if [ "${1:0:1}" = '-' ]; then
set -- mysqld "$@"
fi
# 解析参数,是否是获取帮助信息参数,并设置wantHelp值
#####################################################
# skip setup if they want an option that stops mysqld
wantHelp=
for arg; do
case "$arg" in
-'?'|--help|--print-defaults|-V|--version)
wantHelp=1
break
;;
esac
done
#############################
# 从文件中读取变量值
#############################
# usage: file_env VAR [DEFAULT]
# ie: file_env 'XYZ_DB_PASSWORD' 'example'
# (will allow for "$XYZ_DB_PASSWORD_FILE" to fill in the value of
# "$XYZ_DB_PASSWORD" from a file, especially for Docker's secrets feature)
file_env() {
local var="$1"
local fileVar="${var}_FILE"
local def="${2:-}"
if [ "${!var:-}" ] && [ "${!fileVar:-}" ]; then
echo >&2 "error: both $var and $fileVar are set (but are exclusive)"
exit 1
fi
local val="$def"
if [ "${!var:-}" ]; then
val="${!var}"
elif [ "${!fileVar:-}" ]; then
val="$(< "${!fileVar}")"
fi
export "$var"="$val"
unset "$fileVar"
}
###########################################################################
# 运行mysqld --help --verbose --help 2>&1 >/dev/null命令,
# 此命令会检查配置文件,若配置文件没问题,则成功,不成功则输出错误信息,及if中添
# 加!取不成功。
###########################################################################
_check_config() {
toRun=( "$@" --verbose --help )
if ! errors="$("${toRun[@]}" 2>&1 >/dev/null)"; then
cat >&2 <<-EOM
ERROR: mysqld failed while attempting to check config
command was: "${toRun[*]}"
$errors
EOM
exit 1
fi
}
# 1. $1参数为mysqld 以及 wanthelp 参数为空 以及root用户,执行此代码;
# 2. _check_config检查配置文件是否正确
# 3. 获取DATADIR目录,执行mysqld --verbose --help --log-bin-index=/tmp/tmp.4SyApJWeIo| \
# awk '$1 == "'"datadir"'" { print $2; exit }'
# 4. 创建并修改目录权限
# 5. 执行exec gosu mysql docker-entrypoint.sh "$@",即重新以mysql用户再次调用脚
# 本
# allow the container to be started with `--user`
if [ "$1" = 'mysqld' -a -z "$wantHelp" -a "$(id -u)" = '0' ]; then
_check_config "$@"
DATADIR="$(_get_config 'datadir' "$@")"
mkdir -p "$DATADIR"
chown -R mysql:mysql "$DATADIR"
exec gosu mysql "$BASH_SOURCE" "$@"
fi
# 1. $1参数为mysqld 以及 wanthelp 参数为空,执行此代码,及exec gosu会执行此代码;
if [ "$1" = 'mysqld' -a -z "$wantHelp" ]; then
# 2. 仍然检查配置文件以及获取datadir目录
# still need to check config, container may have started with --user
_check_config "$@"
# Get config
DATADIR="$(_get_config 'datadir' "$@")"
# 3. 若mysql数据库未创建,则执行本段逻辑
if [ ! -d "$DATADIR/mysql" ]; then
# 4. 检查是否设置变量,如root密码、允许root密码为空亦或者随机密码
file_env 'MYSQL_ROOT_PASSWORD'
if [ -z "$MYSQL_ROOT_PASSWORD" -a -z "$MYSQL_ALLOW_EMPTY_PASSWORD" -a -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
echo >&2 'error: database is uninitialized and password option is not specified '
echo >&2 ' You need to specify one of MYSQL_ROOT_PASSWORD, MYSQL_ALLOW_EMPTY_PASSWORD and MYSQL_RANDOM_ROOT_PASSWORD'
exit 1
fi
# 5. 创建目录
mkdir -p "$DATADIR"
# 6. 执行mysqld命令初始化数据库
echo 'Initializing database'
"$@" --initialize-insecure
echo 'Database initialized'
# 7. command -v mysql_ssl_rsa_setup检查命令是否可执行,以及是否存在
# server-key.pem文件,若不存在,则生成证书
if command -v mysql_ssl_rsa_setup > /dev/null && [ ! -e "$DATADIR/server-key.pem" ]; then
# https://github.com/mysql/mysql-server/blob/23032807537d8dd8ee4ec1c4d40f0633cd4e12f9/packaging/deb-in/extra/mysql-systemd-start#L81-L84
echo 'Initializing certificates'
mysql_ssl_rsa_setup --datadir="$DATADIR"
echo 'Certificates initialized'
fi
# 8. 获取socket值并启动mysql
SOCKET="$(_get_config 'socket' "$@")"
"$@" --skip-networking --socket="${SOCKET}" &
pid="$!"
# 9. 设置mysql变量(列表形式),而后可以${mysql[@]}调用
mysql=( mysql --protocol=socket -uroot -hlocalhost --socket="${SOCKET}" )
# 10. 运行30次,验证mysql是否已经启动完毕
for i in {30..0}; do
if echo 'SELECT 1' | "${mysql[@]}" &> /dev/null; then
break
fi
echo 'MySQL init process in progress...'
sleep 1
done
# 11. 若i为0值,则表明mysql启动失败
if [ "$i" = 0 ]; then
echo >&2 'MySQL init process failed.'
exit 1
fi
# 11. 解决时区bug
if [ -z "$MYSQL_INITDB_SKIP_TZINFO" ]; then
# sed is for https://bugs.mysql.com/bug.php?id=20545
mysql_tzinfo_to_sql /usr/share/zoneinfo | \
sed 's/Local time zone must be set--see zic manual page/FCTY/' | "${mysql[@]}" mysql
fi
# 12. 生成root随机密码
if [ ! -z "$MYSQL_RANDOM_ROOT_PASSWORD" ]; then
export MYSQL_ROOT_PASSWORD="$(pwgen -1 32)"
echo "GENERATED ROOT PASSWORD: $MYSQL_ROOT_PASSWORD"
fi
# 13. 若MYSQL_ROOT_HOST不为空亦或者不为localhost,则创建root用户
rootCreate=
# default root to listen for connections from anywhere
file_env 'MYSQL_ROOT_HOST' '%'
if [ ! -z "$MYSQL_ROOT_HOST" -a "$MYSQL_ROOT_HOST" != 'localhost' ]; then
# no, we don't care if read finds a terminating character in this heredoc
# https://unix.stackexchange.com/questions/265149/why-is-set-o-errexit-breaking-this-read-heredoc-expression/265151#265151
read -r -d '' rootCreate <<-EOSQL || true
CREATE USER 'root'@'${MYSQL_ROOT_HOST}' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}' ;
GRANT ALL ON *.* TO 'root'@'${MYSQL_ROOT_HOST}' WITH GRANT OPTION ;
EOSQL
fi
# 14. 为'root'@'localhost'重置root密码
# 使用$rootCreate创建root
"${mysql[@]}" <<-EOSQL
-- What's done in this file shouldn't be replicated
-- or products like mysql-fabric won't work
SET @@SESSION.SQL_LOG_BIN=0;
SET PASSWORD FOR 'root'@'localhost'=PASSWORD('${MYSQL_ROOT_PASSWORD}') ;
GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION ;
${rootCreate}
DROP DATABASE IF EXISTS test ;
FLUSH PRIVILEGES ;
EOSQL
# 15. 已设置root密码,故mysql需加上root密码
if [ ! -z "$MYSQL_ROOT_PASSWORD" ]; then
mysql+=( -p"${MYSQL_ROOT_PASSWORD}" )
fi
# 16. 若配置了MYSQL_DATABASE变量,则创建
file_env 'MYSQL_DATABASE'
if [ "$MYSQL_DATABASE" ]; then
echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` ;" | "${mysql[@]}"
mysql+=( "$MYSQL_DATABASE" )
fi
# 17. 在数据库内创建用户
file_env 'MYSQL_USER'
file_env 'MYSQL_PASSWORD'
if [ "$MYSQL_USER" -a "$MYSQL_PASSWORD" ]; then
echo "CREATE USER '$MYSQL_USER'@'%' IDENTIFIED BY '$MYSQL_PASSWORD' ;" | "${mysql[@]}"
if [ "$MYSQL_DATABASE" ]; then
echo "GRANT ALL ON \`$MYSQL_DATABASE\`.* TO '$MYSQL_USER'@'%' ;" | "${mysql[@]}"
fi
echo 'FLUSH PRIVILEGES ;' | "${mysql[@]}"
fi
# 18. 执行/docker-entrypoint-initdb.d目录下面的脚本,包含shell、sql
echo
for f in /docker-entrypoint-initdb.d/*; do
case "$f" in
*.sh) echo "$0: running $f"; . "$f" ;;
*.sql) echo "$0: running $f"; "${mysql[@]}" < "$f"; echo ;;
*.sql.gz) echo "$0: running $f"; gunzip -c "$f" | "${mysql[@]}"; echo ;;
*) echo "$0: ignoring $f" ;;
esac
echo
done
# 19. 设置root密码是否过期
if [ ! -z "$MYSQL_ONETIME_PASSWORD" ]; then
"${mysql[@]}" <<-EOSQL
ALTER USER 'root'@'%' PASSWORD EXPIRE;
EOSQL
fi
# 20. kill -s TERM "$pid" 杀掉mysql进程,执行成功则返回0,而!kill取反,即kill成
# 功后才执行后面的!wait命令
if ! kill -s TERM "$pid" || ! wait "$pid"; then
echo >&2 'MySQL init process failed.'
exit 1
fi
# 21. 初始化成功后,再次启动
echo
echo 'MySQL init process done. Ready for start up.'
echo
fi
fi
# 22. 正式启动数据库
exec "$@"