The last couple of days I’ve been thinking about setting up a local copy of my websites on my laptop so that I can develop them before I make them live.
Last night I enabled PHP on the apache server built into Mac OSX on my new laptop and installed MySQL on it. I also set up some bash aliases to rsync commands so that I could synchronise the websites from the server to the laptop and back again.
Now that I had local copies of the sites that are synchronised it was time to turn my attention to synchronising the databases between the server and my local machine. I could of configured the server’s MySQL installation to allow remote connections, however, I did not want to do this for security reasons. I decided that I would connect to the MySQL server over SSH by forwarding a port on my local machine to a remote port on the server.
First I needed to create an SSH tunnel using the following command
ssh -fNg -L 3307:127.0.0.1:3306 server.host.name
The options for SSH are
- Requests SSH to background so that you do not have to keep a terminal connected to the server open
- Does not execute a remote command (useful for just forwarding ports)
- Allows remote hosts to connect to local forwarded ports
- Specifies that a local port (3307) is forwarded to the given host (server.host.name) and port (3306)
I created an alias to that command for easy use in future but I’ll need to make sure the tunnel is active before trying to connect to the remote server.
Next its time to turn our attention to actually connecting to the remote MySQL server.
mysql -h 127.0.0.1 -P 3307 -u username -p
- h specifies the host to connect to (must be 127.0.0.1)
- P specifies the port to connect to (your locally forwarded port)
- u specifies the username to connect with
- p will prompt you for your password (–password=passtext can be used to give the password)
Thats if I wanted to connect to the remote MySQL server on the command line. The latest phpmyadmin has an option for syncronizing databases in which case you can put the above details and it will compare the databases and allow you to choose what to synchronise.