Clone a running Pi

Let’s say you have a Raspberry Pi running a web site (like this one) and want to have a backup.

It turns out with a little netcat magic, you can do just that.

1. ssh to the pi, and run this (for Raspbian or other Linux distros)

sudo netcat -l 2222 < /dev/mmcblk0

or, for FreeBSD

sudo netcat -l -p 2222 < /dev/mmcsd0

2. On your “regular” computer (in my case a Mac mini), run this

netcat 2222 > ~/Documents/pi.img

3. Grab a new micro SD card and copy the pi.img image onto it. You can see how here. I use df to figure out which /dev/disk device is the SD card, then use Disk Utility to unmount anything on that card, then I use dd to do the copy, e.g.

sudo dd if=~/Documents/pi.img of=/dev/rdisk4 bs=1m

4. Grab a spare Pi, plug in the SD card, plug it into a power source and let it boot.

5. Make sure you can load a page on the web site, then unplug the network cable from the old Pi and plug it into the new Pi. Now make sure you can reload the page. Or load a different page.

6. Profit.


If your Pi is in the middle of some database operations or someone happens to be updating the website while you’re doing the netcat, the result might not be great. If you find that your copy isn’t working, try shutting down any services like MySQL or Apache before you do the netcat.

Security! If you set up netcat like this and don’t prevent other people from getting at port 2222 (or whatever port you pick), someone else can beat you to it and slurp out your entire SD card’s contents.

Your new SD card has to have the same or greater capacity. Note that not all SD cards labeled 8GB or 16GB, etc. are the same size. Either make sure you have two of the same brand and model, or you might have to use a bigger one for the clone.

Maybe a hold-over from my old UNIX days, but back then the raw device tended to be faster than the block device. I think using /dev/disk4 and /dev/rdisk4 (or whatever number yours is) is pretty much the same.

This is not a substitute for a regular backup scheme. I just want to be able to have something like a hot spare that I can pop in and get running almost instantly if something goes wrong. Cloning once a week (or in the case of this blog, every few years the way I’ve been going) is good enough. Testing the clone every so often is a great idea, too.

If you don’t have netcat on your Mac, you can get it using Homebrew.

Posted in Pi, Random