Skip to content

Instantly share code, notes, and snippets.

@Lycheejam
Last active November 24, 2019 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lycheejam/6d594adaadbdc23b4f2ecb55f4b18e57 to your computer and use it in GitHub Desktop.
Save Lycheejam/6d594adaadbdc23b4f2ecb55f4b18e57 to your computer and use it in GitHub Desktop.
dockerのmysqlからmysqldumpとデータリストアが出来るシェル
#!/bin/sh
#
# database dump & restore for docker mysql
#
ACTION=$1
help() {
cat << EOS
usage: $0 dump
$0 restore
EOS
exit 1
}
check() {
if [ -z "$(docker ps -f name=dbcontainer -q)" ]; then
echo "[skip] dbcontainer is not running"
exit 0
fi
}
restore() {
echo "data restore start"
for file in data/*.sql
do
echo "$file"
docker exec -i dbcontainer sh -c "MYSQL_PWD=password mysql -u testuser testdb" < "$file"
done
if [ $? != 0 ]; then
echo "data restore failed"
exit 1
fi
echo "data restore end"
}
dump() {
echo "mysqldump start"
docker exec -i dbcontainer sh -c "(echo 'show tables' | MYSQL_PWD=password mysql -u testuser testdb | sed -e '1d' > /bkup/all_tables.txt;)"
docker exec -i dbcontainer sh -c "(while read line; do echo \$line; MYSQL_PWD=password mysqldump -u testuser testdb \$line --opt | sed '/^-- Dump completed on/d' > /bkup/\$line.sql; done < /bkup/all_tables.txt;)"
if [ $? != 0 ]; then
echo "mysqldump failed"
exit 1
fi
echo "mysqldump end"
}
case "$ACTION" in
dump) check && dump;;
restore) check && restore;;
*) help;;
esac
exit 0
@Lycheejam
Copy link
Author

コンテナ名 = dbcontainer

@Lycheejam
Copy link
Author

ローカルの./dataディレクトリとコンテナ内の/bkupディレクトリはvolumesでマウント済みであること。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment