Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate MySQL database via SSH

Let's say that I have database1 and database2.

database1 - contains data

database2 - is empty.


I want to copy all data from database1 to database2 via SSH - duplicate database1.

What command should I use?


I have tried

mysqldump -u user -p database1 > database1.sql
Enter password: mysqldump: Got error: 1045: Access denied for user 'user'@'localhost' (using password: NO) when trying to connect
like image 685
enloz Avatar asked Jan 15 '12 11:01

enloz


People also ask

How do you duplicate a database?

On either the source or destination SQL Server instance, launch the Copy Database Wizard in SQL Server Management Studio from Object Explorer and expand Databases. Then right-click a database, point to Tasks, and then select Copy Database.

Can I copy MySQL data directory to another server?

There are broadly two options. Transfer the /var/lib/mysql dir to the new server as it is or do an export and import process. Copying the whole mysql directory will mean less data being transferred and an exact replication of the database from one machine to the other.


2 Answers

Duplicate a MySQL database over SSH in just one command:

mysqldump -u <local-user> -p <local-db> | gzip | ssh user@hostname \
  "gunzip | mysql -u <remote-user> -p<password> <remote-db>"

Note that you must create the remote database first.

More advanced version:

mysqldump -u <local-user> -p <local-db> | xz | pv -W | ssh user@hostname \
"tee remote-dump.sql.xz | unxz | mysql -u <remote-user> -p<password> <remote-db>"

The advanced version:

  • has better compression using xz/unxz (Though take care that compression speed doesn't become a bottleneck - if xz is at 100% CPU then it has probably become a bottleneck and you might be better off with gzip)

  • shows a progress indicator using pv

  • saves a copy of the dump using tee

Only one problem I haven't solved is how to avoid specifying the password in the remote command. It would be really nice to be able to enter this password interactively on the command line – if anyone knows how, please chime in.

like image 188
James Avatar answered Sep 29 '22 17:09

James


This will copy database from S1 to S2

mysqldump --opt <database> | gzip -c | ssh user@wherever 'cat > /tmp/yourfile.sql.gz'

Unzip file

gunzip /tmp/yourfile.sql.gz

Next you'll have to import on S2

mysql -h<host> -u<user> -p<password> < /tmp/yourfile.sql

enjoy

like image 21
danielpopa Avatar answered Sep 29 '22 17:09

danielpopa