Skip to content

Instantly share code, notes, and snippets.

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 hugomaiavieira/1da66c02e65c932cd4f29855e45ee83c to your computer and use it in GitHub Desktop.
Save hugomaiavieira/1da66c02e65c932cd4f29855e45ee83c to your computer and use it in GitHub Desktop.
Mysql dump and restore using docker

Mysql dump and restore using docker

1. Setup the variables

Create a file defining the following variables, with the name .env-for-dump, for example.

export MYSQL_CONTAINER=
export MYSQL_ORIGIN_PASSWORD=
export MYSQL_ORIGIN_USERNAME=
export ORIGIN_DB_NAME=
export MYSQL_TARGET_PASSWORD=
export MYSQL_TARGET_USERNAME=
export TARGET_DB_NAME=

Then load those variables on the terminal session by running source .env-for-dump.

2. Generate the origin database dump

docker exec -i $MYSQL_CONTAINER mysqldump --skip-comments -h host_name -u $MYSQL_ORIGIN_USERNAME -p"$MYSQL_ORIGIN_PASSWORD" $ORIGIN_DB_NAME > dump.sql

Note: Do not use the --compact option. This will make MySQL check your constraints which will cause troubles when using the dump file.

3. Create the target databse

docker exec $MYSQL_CONTAINER sh -c "echo \"CREATE DATABASE $TARGET_DB_NAME;\" | mysql -u $MYSQL_TARGET_USERNAME -p\"$MYSQL_TARGET_PASSWORD\""

3. Load the dump into the target database

Copy the dump file to the mysql container and load it into the database.

docker cp dump.sql $MYSQL_CONTAINER:/dump.sql
docker exec $MYSQL_CONTAINER sh -c 'mysql -u $MYSQL_TARGET_USERNAME -p"$MYSQL_TARGET_PASSWORD" $TARGET_DB_NAME < /dump.sql'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment