Move Drupal Site to Another Server Via Command Line

There are many times, for one reason or another, that I need to transfer a Drupal website from one server to another. I was used to using tools like Filezilla and phpMyAdmin to get most of the heavy lifting done, but after doing this many times I've found the command line to be my friend.

I use linode.com so I know how my server is configured, what's installed, and more importantly have shell access. If you use a shared host this guide/checklist probably won't help you out too much.

To prep the site I do a couple of quick changes:

  • Set to offline mode to prevent any more changes taking place in the database
  • Turn off caching/compressing mechanisms and flush all caches

Once those are done, here are the steps I use to transfer the site:

In my case the folder structure is usually set to something like the following:

/home/user/www/example.com
  /cgi-bin
  /htdocs
  /logs

So start by moving to the root directory of the website you want to transfer.

cd /home/user/www

Create a tarball of current site files. The resulting file will contain all the files we need to transfer to our new server.

tar -zcvf example.com.tar.gz example.com

Make a dump of mysql database.

mysqldump -u [user] -p [databasename] > example.com.sql

Use scp to transfer files to target server

scp -P [port] example.com.tar.gz user@example.com:~/

scp -P [port] example.com.sql user@example.com:~/

Extract tarball on new server in appropriate directory

tar -zxvf example.com.tar.gz

Create new database

mysql -u root -p
[enter password]
create database 'database';

Create new user on the database

CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';

Note: If you need to see what users are already created or need to delete a user you can use these commands:

SELECT host, user from mysql.user;
DELETE FROM mysql.user WHERE user='username';

GRANT ALL ON 'database'.* TO 'user'@'localhost';
FLUSH PRIVILEGES;
QUIT

Restore MySQL dump to new database

mysql -u root -p database < /path/to/example.com.sql;

Change the drupal settings.php file to correspond with new database and user that you created earlier

$db_url = 'mysqli://[user]:[password]@localhost/[database name]';

Enable the website in apache

sudo a2ensite example.com

Reload apache

sudo /etc/init.d/apache2 reload

You might need to update the permissions on the site/default/files folder for apache to access

sudo chgrp -R www-data /var/www/html

Also a good idea to add a cron job for the site. This will run the cron script at 1:10a.m. everyday.

10 1 * * * /usr/bin/wget -O - -q -t 1 http://www.example.com/cron.php