Prepare a VirtualBox Image for Sharing

I prepared a virtual machine image for a course in the uni. The last stage – cleanup, is less trivial than I expected. I’ll take some notes, before I forget. This could serve as a checklist.

This is a Debian 11 guest system

Install all the packages you need

this is specific to the task, nothing to notable here. except for this one:

(Optionally) Install Virtual Box
the VirtualBox guest additions provide better integration of host/guest, including mouse grabbing, auto scaling etc.. and also file sharing. Follow the link [1] to install proper packages.

Additionally, to enable file sharing, in the guest OS:

sudo adduser <username> vboxsf

clean things up in the Guest

(Optionally) set package sources to non-free

in /etc/apt/sources.list, set package sources to main contrib non-free and do apt update, apt dist-upgrade

Remove unused packages

for example:

apt purge $( dpkg -l|fgrep libreoffice|awk '{print $2}' ) gimp libgimp2.0 \
gimp-help-common gimp-data openjdk-11-jre-headless fonts-noto-cjk \
fonts-noto-extra aspell wpolish &&\
apt autoremove &&\
apt clean

Remove old kernels
Debian keeps the old kernels when updating to new ones. It makes no sense to keep them in the VM Image:

  1. find the current kernel version (to keep) with uname -a
  2. list installed kernels, and the headers: dpkg --list | egrep 'linux-image|linux-headers'
  3. remove the old ones with sudo apt --purge remove <things>, if apt autoremove doesn’t do it for you.

Clear browser cache
Do whatever you need..

Clear journald logs

sudo journalctl --rotate
sudo journalctl --vacuum-time=1s

Clear bash history

cat /dev/null > ~/.bash_history && history -c && exit

Trim down the Image

if you use a virtual disk (.vdi) for your guest VM, the .vdi disk doesn’t shrink even if you delete things in the guest fs. Because remove only means they are unlinked. The data is still there if you don’t explicitly free them.

For this you need the zerofree (install with package manager).

reboot into recovery mode (by selecting Advanced Options) in the grub startup menu. Use root password to log in (you may not see the prompt..just type in the password), stop journald service and swap (because they make your disk busy):

systemctl stop systemd-journald.socket
systemctl stop systemd-journald.servide
swapoff -a 0v

remount the root:

mount -o remount,ro /

free up disk (in this case, /dev/sda1) and shutdown

zerofree -v /dev/sda1

compress .vdi drive Go to the virtual machine directory (where the virtual disk file lives)

vboxmanage modifymedium --compact NAME-OF-DRIVE.vdi