I’m sure you know the feeling, you have just got you system working exactly how you want and have decided to take a backup (actually you want to take two backups).
Problem is that you really want to clean up things first to minimize the size of the image and remove any ‘unwanted’ files.
The following steps will clean up the package cache, remove any old log files and history files, and overwrite the free space on the disk with zeros so that the unused space is compressed when you create the image.
To do this I prefer to log-in from another system using the serial console or a remote terminal session as this means that you can just paste the commands into the window don’t have to type them in again. If don’t have another machine switch to the console using CTRL-ALT-F1 (press the control and alt keys together, then without releasing them press the F1 key).
Start by logging in as root and stopping any display managers.
# /etc/init.d/lightdm stop
# /etc/init.d/gdm3 stop
# /etc/init.d/gdm stop
# /etc/init.d/kdm stop
Then save some space by clearing out the package cache.
# apt-get autoremove --purge; apt-get autoclean; apt-get clean
# find /var/cache/ -type f -not -name localelist -delete -print
Forcing new log files to be created and then deleting the backups will keep the size of any log files to a minimum.
# logrotate -f /etc/logrotate.conf; logrotate -f /etc/logrotate.conf
# find /var/log -name '*.[0-9]*' -delete -print
# find /var/log -name '*.gz*' -delete -print
Remember to remove the network and cd rules files if you are going to restore the image on to a different system.
# find /etc/udev/rules.d -name '70-per*-*.rules' -delete -print
Tidy up by deleting any unwanted backup and history files.
# find / -name '*~' -delete -print
# history -c ;find / -name '.bash_history' -delete -print
Finally before creating a backup image of the partition overwrite the unused disk space to erase any unwanted data. This will allow the empty space to be compressed and prevent the backup image from being larger that necessary.
# history -c;dd if=/dev/zero of=/nul;sync;sync;sync;rm /nul;sync
Then insert a bootable cd and reboot to take your backup.
# history -c;reboot