Setting up KVM, Alpine, Docker, K3S, DNSMasq and NetworkManager

Published (last updated )

[[TOC]]

So you want a little bit more control and understanding about running Kubernetes. Your Minikube keeps mysteriously crashing and you’ve had it. Time to do this the hard way, and run a DIY Kubernetes.

Turns out it’s not that difficult or even that much work. There are quite a few steps to follow, but after you’ve followed the steps documented in this guide, you will have gained a better understanding of the various moving parts in a Kubernetes environment, and wil be running your own stable environment.

We’re going to set up KVM and libvirt and use virt-manager to create an Alpine Linux virtual machine. After that we’re going to configure it as a Docker and K3S (a Kubernetes distribution maintained by Rancher) service.

After we’ve done the above, we have a working Docker + Kubernetes environment we can use, but there is one missing piece of the puzzle. We need to set up DNS with a wildcard record to point to the ingress controller of our fresh and shiny Kubernetes virtual machine.

Let’s start with a list of the software we’re going to use. This guide assumes you want to run Docker + Kubernetes on your Linux laptop/desktop, isolated in a virtual machine, and that’s exactly what we’re going to do (note: it’s totally possible to follow these steps and use dedicated bare metal or a virtual machine running somewhere else). Without further ado, here are the components:

The host:

The virtual machine:

In the following chapters we’re going to set up these components.

Setting up the host

The host is essentially the box that runs KVM and libvirt. This can be your laptop or desktop, but it can also be a bare-metal host in a rack somewhere.

The KVM, libvirt, virt-manager, DNSMasq and NetworkManager parts of this guide are specific to Linux. Having said that, if you use a totally different hypervisor or some bare-metal box, you could still follow all the steps except for these parts specific to Linux. The only steps that you would then have to do yourself is setting up the DNS wildcard record to point to your Kubernetes box (which is standard DNS fare which you can do with any DNS server or caching resolver).

Background

Before we start with the steps to configure our host system, let me first explain a few things about why we need things like dnsmasq and NetworkManager, with some background about how you actually access a Kubernetes host/cluster.

A note about using DNSMasq and NetworkManager

You might be wondering: “I’m going to set up a Kubernetes box so I can have my very own Docker + Kubernetes cluster to work around with, why do I need a DNS server (DNSMasq) and NetworkManager?”

This is a good question. To understand why, you need to understand how on earth it’s possible that you spin up stuff on Kubernetes and somehow, magically, you can type in the name of your service followed by some (sometimes completely made up!) domain name and it all just works.

How does a DNS wildcard record and an ingress-controller work together

It’s deceptively simple, actually: Kubernetes will have this thing called an ingress-controller. This is nothing more than a reverse proxy (for those unfamiliar: a reverse proxy is an HTTP and/or TCP streams server that serves as an incoming point of requests, that, when configured, knows how to route those requests to the actual apps deployed on Kubernetes). In DNS you have the concept of a wildcard DNS record (a record, usually indicated with an asterisk * that can point to an IP address).

When you point a wildcard DNS record to a reverse proxy server, you make it possible to find and talk to that reverse proxy server under all kinds of names. Let’s see how that works:

If you would repeat the above steps, but with a totally made-up name, i.e., something you haven’t deployed at all, it would work as follows:

Note that the domain of your Kubernetes host and the wildcard DNS record need not be the same at all - you could have your ingress controller running on frank.example.com and have a wildcard DNS record pointing to madlads.com. As long as you configure ingress objects to have names matching what you access it with (frank.example.com. foo.madlads.com, whatever.madlads.com), it will work.

A note about NetworkManager

This guide came to be because I needed to get our environment working locally. I’m using Linux and like other colleagues I have had various hard-to-explain stability issues with minikube. I settled on Docker + K3S because that has proven to be a very stable combination - we run it for our development and test environments too.

NetworkManager can handle setup of multiple types of connections, think Wi-Fi, Ethernet, Bridges, VPN connections, you name it. NetworkManager is near-ubiquitous on Linux-based desktop systems. Therefore, any configuration that plays nice with NetworkManager is a big plus.

NetworkManager essentially has five ways to integrate with DNS resolvers (i.e., your system DNS client that needs to know when to use which DNS configuration especially when multiple connections are active at the same time). They are (quoted from the NetworkManager configuration reference manual):

Note that the plugins dnsmasq, systemd-resolved and unbound are caching local nameservers. So when NetworkManager writes /run/NetworkManager/resolv.conf, the nameserver line there will be 127.0.0.1.

When using dnsmasq and systemd-resolved per-connection added dns servers will always be queried using the device the connection has been activated on.

Some of these options mention the rc-manager setting. This setting essentially entails awareness of NetworkManager of other DNS settings managers. They are:

So TL;DR; to create a Docker + K3S virtual machine, you don’t need DNSMasq or NetworkManager, but in the context of this guide, which is getting it working on your Linux desktop, it is definitely beyond nice-to-have.

A note about DNSMasq

So NetworkManager supports at least three current (not counting the deprecated ones) DNS resolver handlers, why DNSMasq and not systemd-resolved?

Actually, there is no reason you couldn’t do this with systemd-resolved. It’s just that my system does not have systemd, and so I use dnsmasq. If your system uses systemd, then by all means, use the systemd-resolved DNS handler. You would then need to figure out how you tell systemd-resolved to serve a wildcard DNS record for your Docker + K3S host (which I explain how to do for dnsmasq in the “Configuring DNSMasq and NetworkManager” chapter).

Installing packages

Ha! you’re still here. Good. So you’re on your box (be it laptop/desktop/server whatever) and you want to do this. I’m assuming you’re running some Linux distribution of your choice which has something like a package manager.

I’ve figured out which packages you’d need to install for a couple of distros which you’ll find below. Note that on systemd based distributions like Arch, Debian and Fedora, you might not need or want dnsmasq, but would prefer systemd-resolved. Please act accordingly.

libvirt, virt-manager, dnsmasq/systemd-resolved and NetworkManager.

Arch packages

On Arch linux you’ll use pacman to install packages:

pacman -Syu
pacman -S libvirt virt-manager dnsmasq networkmanager

Debian packages

On Debian linux you’ll use apt to install packages:

apt update
apt upgrade
apt install libvirt-clients qemu-kvm libvirt-daemon-system libvirt-daemon libvirt-daemon-driver-qemu virt-manager dnsmasq network-manager

Fedora packages

On Fedora linux you’ll use dnf to install packages:

dnf upgrade
dnf install libvirt virt-manager dnsmasq NetworkManager

Gentoo packages

On Gentoo linux you’ll use emerge to install packages:

emerge --sync
emerge --ask --verbose --update --deep --newuse @world
emerge --ask app-emulation/libvirt app-emulation/virt-manager net-dns/dnsmasq net-misc/networkmanager

Ubuntu packages

On Ubuntu linux you’ll use apt to install packages:

apt update
apt upgrade
apt install libvirt-clients libvirt-daemon qemu-kvm libvirt-daemon-system libvirt-daemon-driver-qemu virt-manager dnsmasq network-manager

Void packages

On Void linux you’ll use xbps-install to install packages:

xbps-install -Suv
xbps-install libvirt virt-manager dnsmasq NetworkManager

Configuring KVM and libvirt

In the previous steps you’ve installed libvirt and virt-manager to be able to create KVM virtual machines on your linux hosts. In this chapter we’re going to configure libvirt to run at boot, setup authentication and (optionally) configure a network bridge device for directly servicing your local network instead of a local-only nat’ed network on your host.

Enable start at boot for libvirt services

After you’ve installed libvirt, you need to make sure that the service runs at boot, else every time you start your system, you have to manually start libvirt before you can start/stop a virtual machine.

Enabling start at boot on Arch

On Arch linux you’ll use systemctl to configure services to run:

systemctl enable libvirtd.service
systemctl enable virtlogd.service
systemctl start libvirtd.service
systemctl start virtlogd.service

Note: I’m not 100% sure about the above service names, needs to be verified. I do know you need to run at least libvirtd and virtlogd.

Enabling start at boot on Debian

On Debian linux you’ll use systemctl to configure services to run:

systemctl enable libvirtd.service
systemctl enable virtlogd.service
systemctl start libvirtd.service
systemctl start virtlogd.service

Note: I’m not 100% sure about the above service names, needs to be verified. I do know you need to run at least libvirtd and virtlogd.

Enabling start at boot on Fedora

On Fedora linux you’ll use systemctl to configure services to run:

systemctl enable libvirtd.service
systemctl enable virtlogd.service
systemctl start libvirtd.service
systemctl start virtlogd.service

Note: I’m not 100% sure about the above service names, needs to be verified. I do know you need to run at least libvirtd and virtlogd.

Enabling start at boot on Gentoo

On Gentoo linux you’ll use rc-update to configure services to run:

rc-update add libvirtd default
rc-update add virtlogd default

Note: I’m not 100% sure about the above service names, needs to be verified. I do know you need to run at least libvirtd and virtlogd.

Enabling start at boot on Ubuntu

On Ubuntu linux you’ll use systemctl to configure services to run:

systemctl enable libvirtd.service
systemctl enable virtlogd.service
systemctl start libvirtd.service
systemctl start virtlogd.service

Note: I’m not 100% sure about the above service names, needs to be verified. I do know you need to run at least libvirtd and virtlogd.

Enabling start at boot on Void

On Ubuntu linux you’ll use ln to configure services to run:

cd /var/service
ln -s /etc/sv/libvirtd
ln -s /etc/sv/virtlogd

Setting up authentication for libvirt

To make sure we can create and manage virtual machines without being root all the time, we need to add our user to the right groups and we need to set a few things in the /etc/libvirt configuration directory.

Make sure user is member of kvm and libvirt groups

First, we make sure our current user is in the right groups. These usually are kvm and libvirt. You can edit /etc/group and/or /etc/gshadow directly, use vigr and vigr -s or use utilities like adduser or useradd to do it.

Do note that if the user chosen is the current user, you will need to log out and back in for the new group memberships to take effect.

Make sure permissions on libvirt configuration files are correct

Permissions in /etc/libvirt are often not consistent, let’s fix that:

chown -R root:libvirt /etc/libvirt
find /etc/libvirt -type d -exec chmod 775 {} \;
find /etc/libvirt -type f -exec chmod 664 {} \;

Note: the above permissions are fine for a personal system. You might want to evaluate if they’d be ok for a shared system or server (you could also set 770 and 660 respectively, or on a remote-only / no-user system 750 and 640).

Make sure libvirt socket permissions are correct

As you might have noticed, libvirt has a lot of configuration files. You’ll also notice that many of them contain similar settings, in particular for group permissions on sockets, group names, etc.

We’re going to use find and sed to consitently configure these things. Let’s first make a backup of our config, in case anything goes wrong:

cp -Rpd /etc/libvirt /etc/libvirt.orig

Now, let’s make sure a user in the libvirt group can access any libvirt read-only, read-write or admin socket:

find /etc/libvirt -type f -exec sed -i 's/unix_sock_group = "[[:alnum:]]"/unix_sock_group = "libvirt"/g' {} \;
find /etc/libvirt -type f -exec sed -i 's/unix_sock_ro_perms = "[[:digit:]]"/unix_sock_ro_perms = "0770"/g' {} \;
find /etc/libvirt -type f -exec sed -i 's/unix_sock_rw_perms = "[[:digit:]]"/unix_sock_rw_perms = "0770"/g' {} \;
find /etc/libvirt -type f -exec sed -i 's/unix_sock_admin_perms = "[[:digit:]]"/unix_sock_admin_perms = "0770"/g' {} \;

Make sure the above settings are uncommented:

find /etc/libvirt -type f -exec sed -i 's/#unix_sock_group = /unix_sock_group = /g' {} \;
find /etc/libvirt -type f -exec sed -i 's/#unix_sock_ro_perms = /unix_sock_ro_perms = /g' {} \;
find /etc/libvirt -type f -exec sed -i 's/#unix_sock_rw_perms = /unix_sock_rw_perms = /g' {} \;
find /etc/libvirt -type f -exec sed -i 's/#unix_sock_admin_perms = /unix_sock_admin_perms = /g' {} \;

Make sure our socket authentication method is polkit:

find /etc/libvirt -type f -exec sed -i 's/auth_unix_ro = "[[:alnum:]]"/auth_unix_ro = "polkit"/g' {} \;
find /etc/libvirt -type f -exec sed -i 's/auth_unix_rw = "[[:alnum:]]"/auth_unix_rw = "polkit"/g' {} \;

And make sure the above settings are uncommented:

find /etc/libvirt -type f -exec sed -i 's/#auth_unix_ro = "/auth_unix_ro = /g' {} \;
find /etc/libvirt -type f -exec sed -i 's/#auth_unix_rw = "/auth_unix_rw = /g' {} \;

Make sure you restart your libvirtd and virtlogd services so they will use these new settings.

Make sure polkit rules are in place for libvirt

In some (all?) cases, policy kit (a.k.a. polkit) needs to know that being a member of the libvirt group is enough and satisfies an authenticated constraint. We do this by adding a rule file in /etc/polkit-1/rules.d:

cat <<EOF >/etc/polkit-1/rules.d/30-libvirt.rules
polkit.addRule(function(action, subject) {
    if ((action.id == "org.libvirt.unix.monitor" ||
	 action.id == "org.libvirt.unix.manage") &&
        subject.isInGroup("libvirt"))
    {
        return polkit.Result.YES;
    }
});
EOF

Users or administrators should never need to start polkitd as it will be automatically started by dbus-daemon, which is responsible for its lifetime. Since this service interacts with the desktop manager it is safer to log out completely and log in again. You will know the above worked when you start virt-manager and when connecting to the local Qemu system, are not prompted for a password.

Make sure client utilities use the right libvirt URI

For some reason, by default, the client utilities, like virsh don’t talk to the system url, which means that commands like virsh list return nothing, even though a virtual machine is running. Running the same command as root would work, which is annoying. You can fix this by adding to following to your ~/.bashrc (or other shell you might prefer):

shopt -s compat31
isNumber='^[0-9]+$'
if [[ "$(uname -s)" == "Linux" && "$(pgrep libvirtd)" =~ "$isNumber" ]]; then
    export LIBVIRT_DEFAULT_URI=qemu:///system
fi

The above checks if we’re running on linux and if pgrep returns a number for libvirtd which indicates it is running, and if so, sets LIBVIRT_DEFAULT_URI to “qemu:///system”. This results in all libvirt command-line tooling working normally:

# virsh list
 Id   Name    State
-----------------------
 1    xenon   running

Setting up a network bridge (optional)

When you’re running a Linux system that’s using ethernet (either a desktop or a laptop system) you might want to make it possible to connect virtual machines to the network using “bridged” networking.

Bridged networking means that the virtual machine connects directly to the same network that your host desktop or laptop (or server) system connects to.

By default, libvirt only has one network named default that has a random local IP range and uses NAT to access the outside world. This is usually fine, but if you want to make the virtual machine accessible beyond your own computer, you need to connect it to a bridge-type network.

Note that this is not feasible in combination with Wi-Fi adapters. This has to do with a limitation of how many arp mac hardware addresses a Wi-Fi access point can register on a single connection. If you really want to know why, you can read this and this.

We’re first going to create the bridge in NetworkManager using nmcli. After that’s done, we’re going to tell libvirt about it.

Configuring a bridge connection in NetworkManager

As said before, you need one or more ethernet devices, which are probably currently auto-configured by NetworkManager, named “Wired Connection 1” or something similar.

We’re going to remove that connection, create a bridge connection and add the ethernet device as a slave to the bridge. Let’s get started by listing our available connections:

# nmcli con show
NAME               UUID                                  TYPE      DEVICE
Wired Connection 1 ef781df5-8280-4e05-894b-855057a2ad59  ethernet  eth0

The above simply shows one configured ethernet device. You might have more. We’re going to remove this connection, create a bridge connection, add the above ethernet device as a slave, rename the bridge and slave device to something nicer and bring up the bridge:

nmcli con del "Wired connection 1"
nmcli con add type bridge ifname bridge0
nmcli con add type bridge-slave ifname eth0 master bridge0
nmcli con mod bridge-bridge0 con-name bridge0
nmcli con mod bridge-slave-eth0 con-name eth0
nmcli con mod bridge0 ipv4.dns-priority 1
nmcli con up bridge0

A small note about the ipv4.dns-priority setting. NetworkManager will by default set a priority of 100 for local connections and 50 for non-local (usually VPN or Wi-Fi). That means that the DNS search field of a non-local connection would be shoved in front of your own, local DNS search field. Setting the bridge connection to a priority of 1 effectively make the DNS search field of the local connection the first in the list, always. To read up on DNS order settings, see: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/configuring-the-order-of-dns-servers_configuring-and-managing-networking

After a few seconds, you will see your new bridge device receiving an IP address which you can check using ip or ifconfig:

# ip address show bridge0
5: bridge0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether 00:11:22:33:44:55 brd ff:ff:ff:ff:ff:ff
    inet 172.17.1.14/24 brd 172.17.1.255 scope global dynamic noprefixroute bridge0
       valid_lft 50520sec preferred_lft 50520sec

# ifconfig bridge0
bridge0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 172.17.1.14  netmask 255.255.255.0  broadcast 172.17.1.255
        ether 00:11:22:33:44:55  txqueuelen 1000  (Ethernet)
        RX packets 657224  bytes 454939656 (433.8 MiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 640224  bytes 261245824 (249.1 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

You can usually check the system log to see what NetworkManager is doing. On non-systemd systems you can usually do something like tail -f /var/log/messages or tail -f /var/log/syslog.

On systemd-based systems you can use something like journalctl.

Configuring a bridge network in libvirt

Now that we have bridge device at the host level, we need to tell libvirt about it, so libvirt can use the bridge device to enable virtual machine bridged networking.

We first need to create a file named bridged.xml which we will import using the virsh command-line utility. Let’s create the file:

cat <<EOF >/tmp/bridged.xml
<network>
    <name>bridged</name>
    <forward mode="bridge" />
    <bridge name="bridge0" />
</network>
EOF

Now we’re going to import this network definition into libvirt, activate it and configure it to auto start on system boot:

virsh net-define /tmp/bridged.xml
virsh net-start bridged-network
virsh net-autostart bridged-network

Finally, let’s list our networks:

# virsh net-list
 Name      State    Autostart   Persistent
--------------------------------------------
 bridged   active   yes         yes
 default   active   yes         yes
A note about NetworkManager bridge devices and suspend/resume

NetworkManager is essentially oblivious to the dynamic changes that libvirt makes to the bridge configuration. Essentially, whenever a virtual machine with a bridge configuration comes up, a vnet# device is created and added to the bridge device, managed by NetworkManager.

When the system suspends and is later resumed, NetworkManager re-sets-up the bridge in order to re-establish internet-connectivity, which means any vnet# devices added by libvirt are ignored/forgotten, and suddenly not a member device of the bridge.

To fix this, simply re-add the vnet devices to the bridge after resume:

# for device in $(ifconfig -a | grep vnet[0-9] | cut -d: -f1); do sudo brctl addif bridge0 $device; done

Configuring DNSMasq and NetworkManager

So! We now have libvirt running, with the right permissions, the command-line utilities can talk to the right uri and optionally, you’ve also configured a bridge device. Let’s continue and configure NetworkManager to use the dnsmasq caching resolver.

Note: If you’re on a systemd-based system, you might prefer systemd-resolved which is a more-native solution for having a caching resolver on systemd-based systems. This guide will not specifically document how to do that though. At the least you will need to figure out how (if at all possible) you could make systemd-resolved serve a wildcard DNS record.

First, in any case, make sure you are not running dnsmasq as a system service. In our configuration, NetworkManager is responsible for starting and stopping dnsmasq.

Let’s edit the /etc/NetworkManager/NetworkManager.conf file. Under the [main] section, add a line indicating you’ll use dnsmasq as a caching resolver. Here is an example file (yours might be slightly different):

[main]
dns=dnsmasq
plugins=keyfile

[keyfile]
unmanaged-devices=interface-name:docker*;interface-name:virt*;interface-name:vnet*

A small note about the unmanaged-devices line above: This tells NetworkManager to ignore certain devices. The above list effectively ignores interfaces managed by libvirt and docker.

After you’ve made changes to this file, you need to tell NetworkManager to reload itself:

nmcli general reload

If you look at the system log (either /var/log/messages, /var/log/syslog or by using journalctl), you’ll note that NetworkManager is now using dnsmasq to handle dns-related settings. You will also find that NetworkManager itself started a dnsmasq instance for you, which is listening on 127.0.0.1:53.

We now need to tell our system to actually use the resolv.conf that NetworkManager generated for us, which will usually contain a collection of search field entries and, predictably, a nameserver line pointing to the dnsmasq instance running at 127.0.0.1:53. Let’s do that:

mv /etc/resolv.conf /etc/resolv.conf.orig
ln -s /run/NetworkManager/resolv.conf /etc/resolv.conf

Let’s take a look at its contents:

# cat /etc/resolv.conf
# Generated by NetworkManager
search foo.something bar.stuff home.local
nameserver 127.0.0.1
options edns0 trust-ad

Setting up the virtual machine

To create a virtual machine, we’re going to use the virt-manager graphical user interface. You can probably start it from Gnome or KDE or whichever desktop environment you’re using. You can also start it from command-line of course.

First, let’s make sure we can edit XML in various dialogs. To do so, go to the “Edit” pull-down menu and select “Preferences”. Make sure “Enable XML editing” is selected and click “Close”.

In virt-manager, you’ll see a “QEMU/KVM” line which indicates the local libvirt installation. Right-click on that an click “Connect”.

In the top-left corner, you’ll see a screen icon with a light in the corner. The tooltip will say “Create a new virtual machine”. Click it. You’ll be presented with a dialog. Let’s go through it step by step.

  1. Choose how you would like to install the operating system: Choose “Local install media (ISO image or CDROM)”;
  2. Architecture options: Choose x86_64;
  3. Click the “Forward” button in the lower-right of the dialog;
  4. Choose ISO or CDROM install media: Click “Browse…” and select the Alpine linux iso;
  5. De-select “Automatically detect from the installation media/source”;
  6. Choose the operating system you’re installing: Fill in: alpinelinux3.15 (which is the highest available at the time of this writing - we’re installing 3.16 with this guide and it might be that in the future there’s a newer version available - in that case, select the newer version);
  7. Click the “Forward” button in the lower-right of the dialog;
  8. Choose Memory and CPU settings: Set at least 6144 for “Memory”, but the more the better. Set at least 2 for “CPUs”, but again, the more you have, the better;
  9. Click the “Forward” button in the lower-right of the dialog;
  10. Select “Enable storage for this virtual machine”;
  11. Select “Create a disk image for the virtual machine”;
  12. Fill in at least 64 GiB. As always, more is often better;
  13. Click the “Forward” button in the lower-right of the dialog;
  14. In the “Name” field, fill in a good name for your vm - ua good practice is to have this name equal to the lower-case short hostname of the virtual machine;
  15. Select “Customize configuration before install”;
  16. Click on the “Network selection” arrow so it expands. Select either Virtual network 'bridged' or Virtual network 'default';
  17. Click the “Finish” button in the lower-right of the dialog;
  18. You’ll be presented with a new dialog. On the main “Overview” tab, right at the bottom of the page, you’ll see a “Firmware:” setting which is usually set to the default of BIOS. Set this to UEFI;
  19. Click the “Apply” button in the lower-right of the dialog;
  20. In the top-left of the dialog, click “Begin Installation”.

If you followed the above steps correctly, you’ll see Alpine linux booting and you’re ready to continue with the installation steps for Alpine itself.

Installing Alpine

After following the creation steps in the previous chapter, you’ll be presented with a screen that shows that Alpine has booted. Specifically, you’ll see a:

localhost login: _

Blinking at you. Login as root, no password required. You’ll be presented with a welcome message and a hint about running setup-alpine. Let’s run that:

setup-alpine

The installer will waste no time greeting you. Let’s go step-by-step:

  1. First, choose a keyboard layout. Just choose none here;
  2. You’ll be asked for a hostname. You should usually fill in a short, non-fqdn hostname here, matching the name of the virtual machine you selected in the previous steps, when you were creating the virtual machine;
  3. You’ll be asked which network interface you want to use. Just go with the default, which is [eth0] as of this writing;
  4. You’ll be asked what the IP address should be. Just have DHCP handle it so select [dhcp];
  5. You’ll be asked if you want to do any manual network configuration. Just say [no];
  6. Enter a password for the root user;
  7. Select your timezone. For me it’s [CET]; [UTC] is a good generic choice of course;
  8. You’ll be asked if you want to use an HTTP proxy. If you’re not sure, you probably don’t need to set it so select [none];
  9. You’ll be presented with a mirror-list. Just select [1];
  10. You’ll be asked if you want to create a user. Just say [no];
  11. Choose [openssh] as SSH server;
  12. You’ll be asked if you want to allow root login over SSH. Say [yes];
  13. You’ll be asked if you want to conveniently pass along an SSH public key. Feel free to do so or select [none];
  14. You’ll be prompted for a disk to install Alpine to, with a list of available disks. Type in the name of the disk you want to use, like [vda];
  15. You’ll be asked how you want to use it. Select either [sys] or [lvm]. If you selected LVM, you need to select [sys] in the follow-up question. Finally it will give you a warning and ask you if you’re sure. Say [yes];

Alpine will start installing and pretty quick (Alpine is tiny!) you’ll be asked to please reboot, so let’s do so:

reboot

The virtual machine will reboot and you’ll see your freshly installed Alpine linux booting and you’ll be presented with a login screen. This time you’ll need the root password you configured in step six previously if you’d like to do so. We’ll be continuing our work through SSH though, so leave the graphical console alone for now and close it (just close the window).

Setting up a DHCP address reservation for your virtual machine (optional)

If you are running this virtual machine on the Virtual network 'default' network, your virtual machine will get a randomly assigned IP from the embedded DHCP service provided by libvirt. This is not particularly convenient, so let’s make sure we configure a so-called DHCP reservation for our virtual machine:

In the main virt-manager screen, where you’ll also see your virtual machine running. Double-click your virtual machine. It usually opens up the graphical console. In the top-left of the toolbar, you’ll see an icon representing a lamp. Click that and you’ll see your virtual machine settings. In the list of virtual hardware on the left, select the NIC device (usually indentified with an icon showing two arrows pointing left and right). It also has the last three hexidecimal numbers of the MAC address in the name. When you do so, the right part of the screen will show the “Details” tab by default. You’ll see a field called MAC address here. Copy the six-part hexidecimal numbers here. We’ll need this later to configure the reservation.

Close the virtual machine window and go back to the main virt-manager screen.

select the “Edit” pull-down menu and go to “Connection Details”. You’ll be presented with a dialog. Select the “Virtual Networks” tab.

On the right, you’ll see a list of your networks. You’ll see the default network here. If you optionally created the bridged network, you’ll see that one here too. Select the default network. In the tabs directly on the right, you can select “Details” and “XML”. Select the “XML” tab.

You’ll see the XML configuration that represents the default network configuration. Under the <dhcp> block, we need to add a <host> reservation entry. Here’s an example from my box:

<network connections="1">
  <name>default</name>
  <uuid>d2c995d8-df09-4ac8-80d8-82b03b3bc3bd</uuid>
  <forward mode="nat">
    <nat>
      <port start="1024" end="65535"/>
    </nat>
  </forward>
  <bridge name="vir0" stp="on" delay="0"/>
  <mac address="52:54:00:f2:02:39"/>
  <ip address="10.10.11.1" netmask="255.255.255.0">
    <dhcp>
      <range start="10.10.11.2" end="10.10.11.254"/>
      <host mac="52:54:00:f6:65:81" ip="10.10.11.2"/>
    </dhcp>
  </ip>
</network>

Above you see the line:

<host mac="52:54:00:f6:65:81" ip="10.10.11.2"/>

This is the reservation. We previously obtained the MAC address from our virtual machine. You need to put that here, in place of the 52:54:00:f6:65:81 number.

You also need to select an IP address. I observed that this address needs to be within the DHCP range, which in the above example configuration is 10.10.11.2 to 10.10.11.254. You might have a whole different range, configure what you want, but I would not use very common ranges, and especially not ranges that you’re already using on your network!

When you’re done, click the “Apply” button in the lower-right of the dialog. You might observe that the setting immediately disappears! This is actually OK!

Finally, click on the “Stop Network” button in the lower-left of the screen (the X button). After that, click the “Start Network” button. You’ll observe your edits are back again and now active in the running libvirt instance.

You now need to reboot your virtual machine. You can do this by going to the graphical console. From the “Virtual Machine” pull-down menu, select “Shut down” followed by “Reboot”.

When you take a look at the freshly rebooted virtual machine, you’ll see messages from udhcpc indicating the obtained IP address. It should match the IP you configured in the host reservation.

Note: sometimes udhcpc prints to the console that it could not obtain an IP address. In my experience, it’s usually to early when it prints that and under the hood, it actually did obtain an IP address.

Logging in through SSH

So! We now have a virtual machine running, at an IP address we expect and we’re ready to log in. Since working through the graphical console is inconvenient due to copy/paste and such not working, we’re going to continue through SSH.

Open a terminal window on your host machine and start an SSH session to your virtual machine, by using the IP address it has configured. You can usually see the IP address mentioned on the graphical console. For example:

ssh root@10.10.11.2

You’ll need the password you configured in step six of the virtual machine installation chapter.

Logged in? great! Let’s set up our SSH public key, so we don’t have to password so often again.

Installing an SSH public key

Normally installing a public key is optional, but due to how we’ll set up our DOCKER_HOST connection string, we need SSH public key authentication and it needs to be non-interactive. That means either a passwordless key (evil!) or password protected private key combined with an SSH agent.

This guide does not explain how to set that up and assumes you have this running already. If not, go an create a private key, put a good password on it and set up your SSH agent.

Assuming you have a working SSH setup, obtain your SSH public key (something like ~/.ssh/id_rsa.pub or gpg --export-ssh-key someone). Make sure you’re logged in on the virtual machine and place the public key in /root/.ssh/authorized_keys.

Log out and then log in again. You will notice that you’re now using SSH public key authentication instead of using the password of the root user.

All remaining steps within this “Setting up the virtual machine” chapter assume you’re logged in as root on the virtual machine, using SSH.

Installing packages

First, we’re going to enable the Alpine community repository:

sed -i 's/# //g' /etc/apk/repositories

Now update the package index and install any available upgrades (make note of the fact that you see the community repository mentioned in the output - if not, something went wrong in the previous step and you’ll need to edit the /etc/apk/repositories to enable the community repository manually):

apk update
apk upgrade

The previous command might have updated the kernel. If that’s the case, make sure you reboot. Let’s install our packages:

apk add bash bind-tools curl dbus dbus-openrc file git gnupg htop ncurses openldap-clients openssl python3 rsync socat ssmtp docker-compose docker-engine docker-cli

Enable dbus

Dbus is used by K3S service containers. Let’s enable it:

rc-update add dbus default
service dbus start

Configure ssmtp (optional)

If you want your virtual machine to be able to send email through a trusted smarthost relay, you can configure ssmtp which is a tiny SMTP server:

cat <<EOF >/etc/ssmtp/ssmtp.conf
# /etc/ssmtp.conf -- a config file for sSMTP sendmail.
mailhub=smtp.yourdomain.com
FromLineOverride=YES
RewriteDomain=yourdomain.com
EOF

Make sure to replace smtp.yourdomain.com and yourdomain.com with something that make sense for your environment. ssmtp does not run as a service so no need to configure it for startup at boot.

Configuring Docker

In the following chapters, we’re going to configure Docker.

Add docker group

Add a system group for the docker user:

addgroup docker

Enable port forwarding

Enable port forwarding:

echo 'net.ipv4.conf.all.forwarding=1' > /etc/sysctl.d/port-forwarding.conf
/etc/init.d/sysctl restart

Increase max mmap count

Increase the maximum memory map count:

echo 'vm.max_map_count=262144' > /etc/sysctl.d/max-memory-maps.conf
/etc/init.d/sysctl restart

Increase max open files

Increase the maximum open files count

echo 'fs.file-max=65536' > /etc/sysctl.d/max-open-files.conf
/etc/init.d/sysctl restart

Configure docker service to start at boot

Now let’s enable docker to start at boot and start the docker service:

rc-update add docker default
service docker start

Installing K3S

We’re going to install K3S with Docker as the container-runtime, with enabled aggregator routing and without the Traefik ingress controller (the latter because we opt to use the more widely used standard ingress-nginx controller which we’ll install after this). Let’s do it:

curl -sfL https://get.k3s.io | sh -s - --docker --kube-apiserver-arg enable-aggregator-routing=true --disable traefik

The above script will exit sooner than the service actually being up. You can check the services coming up by checking the pod states using kubectl:

# kubectl get pods -n kube-system
NAME                                      READY   STATUS    RESTARTS   AGE
local-path-provisioner-6c79684f77-qhwfh   1/1     Running   0          86s
coredns-d76bd69b-jtj5s                    1/1     Running   0          86s
metrics-server-7cd5fcb6b7-f8hv9           1/1     Running   0          86s

When all pod statusses are “Running”, Kubernetes is up and we can continue the rest of the setup.

Set up an ingress-nginx controller

As mentioned before, we’re opting to use the arguably more widely used ingress-nginx controller instead of K3S’s default Traefik. During the writing of this guide, the latest version was v1.2.1. To see the current stable version, go to https://github.com/kubernetes/ingress-nginx/releases and look for the latest controller release and adjust the URL used below. Onward:

kubectl apply -f "https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.2.1/deploy/static/provider/baremetal/deploy.yaml"

After very few seconds, you’ll be able to see the ingress controllers in their own namespace:

# kubectl get pods -n ingress-nginx
NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-admission-create-f9lx8        0/1     Completed   0          28s
ingress-nginx-admission-patch-r2tv7         0/1     Completed   1          28s
ingress-nginx-controller-5f56d85cfb-r97vm   0/1     Running     0          28s
Enable ingress host network

Make sure ingress-nginx can access the network of its host. Let’s first create the patch file:

cat <<EOF >/tmp/ingress-nginx-enable-host-network.yml
spec:
  template:
    spec:
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      kind: DaemonSet
      reportNodeInternalIp: true
EOF

Use the patch file:

kubectl patch deployment ingress-nginx-controller -n ingress-nginx --patch-file=/tmp/ingress-nginx-enable-host-network.yml
Set ingress class default

Make sure our ingress-nginx’s ingressclass is the default. Create the patch file:

cat <<EOF >/tmp/ingress-nginx-ingressclass-default.yml
metadata:
  annotations:
    ingressclass.kubernetes.io/is-default-class: "true"
EOF

Use the patch file:

kubectl patch ingressclass nginx -n ingress-nginx --patch-file=/tmp/ingress-nginx-ingressclass-default.yml

Workaround for CoreDNS log spam

CoreDNS has an extremely annoying bug that causes it to write WARNING lines to the log file every time their custom settings glob pattern does not find files in its custom directories, which is the default.. Sigh. Let’s fix that:

cat <<EOF >/tmp/coredns-workaround-glob-log-spam.yml
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns-custom
  namespace: kube-system
data:
  empty.server: |
    # empty
EOF

Load the config map:

kubectl apply -f /tmp/coredns-workaround-glob-log-spam.yml

Delete the coredns container, forcing its recreation, which will pick up the previously created config map:

kubectl delete -n kube-system `kubectl get pods -n kube-system -o name --no-headers=true | grep coredns`

Final steps on the host

Alright, you made it this far, which means you’re almost done. You have an Alpine linux virtual machine running, with Docker and K3S running. Let’s configure the wildcard DNS record and make sure we can use our local docker and kubectl command-line tools to talk to our Docker + K3S virtual machine.

The following needs to be done on your desktop/laptop, i.e., the host system and not on the virtual machine.

Configure a wildcard DNS record in dnsmasq pointing to ingress

Remember all that work we did with NetworkManager and dnsmasq? This is where we actually set up the wildcard dns record. Make sure you configure a (sub) domain name you want to use (the yourdomain.com below) and use the IP address you configured for your virtual machine (the 10.10.11.2 below):

mkdir -p /etc/NetworkManager/dnsmasq.d/
cat <<EOF >/etc/NetworkManager/dnsmasq.d/custom-wildcards.conf
address=/yourdomain.com/10.10.11.2
EOF

Reload network manager:

nmcli general reload

Make your local docker command use docker on the virtual machine

To use the docker instance on the virtual machine from somewhere else, you can set the DOCKER_HOST environment variable to point to it. Here’s an example:

export DOCKER_HOST=ssh://root@10.10.11.2

Ideally, you would only set this variable if your machine is up. To do so, you can add the following to your ~/.bashrc (or equivalent if you’re using a different shell than bash):

# Check for a docker host string on this host.
if [ -e "$HOME/.docker/host.string" ]; then
    DOCKER_HOST="$(cat "$HOME/.docker/host.string")"
fi

# Also handle possible minikube usage..
which minikube > /dev/null 2>&1
[ $? == 0 ] &&  minikube status | grep -qw 'apiserver: Running'
if [ $? == 0 ]; then
    eval $(minikube docker-env) && \
    echo "Notice: Minikube is running, setting up DOCKER_HOST=$DOCKER_HOST.."
# Else check if DOCKER_HOST is set..
elif [ ! -z "$DOCKER_HOST" ]; then
    DOCKER_TYPE=$(echo "$DOCKER_HOST" | cut -d: -f1)
    DOCKER_ADDR=$(echo "$DOCKER_HOST" | cut -d: -f2 | sed 's|^.*//||g; s|^.*@||g')
    DOCKER_PORT=$(echo "$DOCKER_HOST" | cut -d: -f3)

    if [ "$DOCKER_TYPE" == "ssh" ]; then
        ping -c 1 -W 1 $DOCKER_ADDR > /dev/null 2>&1 && \
        export DOCKER_HOST && \
        echo "Notice: A Docker remote host is up, setting DOCKER_HOST=$DOCKER_HOST.."
    elif [ "$DOCKER_PORT" == 2376 ]; then
        DOCKER_TLS_VERIFY="1"
        DOCKER_CERT_PATH="$HOME/.docker/certs"

        ping -c 1 -W 1 $DOCKER_ADDR > /dev/null 2>&1 && \
        export DOCKER_HOST DOCKER_TLS_VERIFY DOCKER_CERT_PATH && \
        echo "Notice: A Docker remote host is up, setting DOCKER_HOST=$DOCKER_HOST.."
    else
        ping -c 1 -W 1 $DOCKER_ADDR > /dev/null 2>&1 && \
        unset DOCKER_TLS_VERIFY DOCKER_CERT_PATH && \
        export DOCKER_HOST && \
        echo "Notice: A Docker remote host is up, setting DOCKER_HOST=$DOCKER_HOST.."
    fi
fi

Using the above, you would set your DOCKER_HOST string in ~/.docker/host.string; the above would then check if it’s up, and if so, tell you about it and use it. As a bonus, if you are also (still?) using minikube, it will handle that gracefully also.

To immediately enable the above in your current shell:

source ~/.bashrc

To verify that docker is connecting to the remote dockerd instance, you can issue the following command:

docker info

You’ll note the “Name:” field, which should be the name of your virtual machine.

Make your local kubectl command use kubernetes on the virtual machine

Finally, to be able to talk to your Kubernetes instance on your virtual machine from your desktop/laptop host, you need to make sure your local kubectl and compatible friends like k9s can find it and authorize it. You might already have multiple Kubernetes clusters that you need to interact with, so it would be great if you could come up with a configuration that allows you to easily use multiple so-called Kubernetes “contexts”. Let’s set that up.

Add the following to your ~/.bashrc (or equivalent if you’re not using bash):

if [ -d "$HOME/.kube/config.d" ]; then
    unset KUBECONFIG
    for config in $(find "$HOME/.kube/config.d" -type f | sort); do
        KUBECONFIG+="$config:"
    done
fi

Create the ~/.kube/config.d directory and place your kube config and name this context myk3s (you can choose any name you want, no spaces, lowercase):

mkdir -p ~/.kube/config.d
scp root@10.10.11.2:/etc/rancher/k3s/k3s.yaml ~/.kube/config.d/myk3s.yaml
sed -i 's/current-context: default//g' ~/.kube/config.d/myk3s.yaml
sed -i 's/default/myk3s/g' ~/.kube/config.d/myk3s.yaml
sed -i 's/127.0.0.1/10.10.11.2/g' ~/.kube/config.d/myk3s.yaml

To immediately enable the above in your current shell:

source ~/.bashrc

Show and use your context, list pods:

# kubectl config get-contexts
CURRENT   NAME      CLUSTER   AUTHINFO       NAMESPACE
          myk3s     myk3s     myk3s          default
# kubectl config use-context myk3s
Switched to context "myk3s".
# kubectl get pods -n kube-system
NAME                                      READY   STATUS    RESTARTS   AGE
local-path-provisioner-6c79684f77-qhwfh   1/1     Running   0          58m
metrics-server-7cd5fcb6b7-f8hv9           1/1     Running   0          58m
coredns-d76bd69b-6mslm                    1/1     Running   0          35m