Before SystemD came out, if you wanted to set DNS servers statically, you’d just edit your network config file, set the DNS servers there, restart the networking service and everything would work as expected.
Let’s say that you tell systemd-resolved to use the following DNS servers:
If the first one fails, resolved should use 1.1.1.1.
But is this what actually happens?
Not at all!
Instead of 1.1.1.1, resolved uses 8.8.8.8 which you’ve never specified anywhere.
Not only does it switch to 8.8.8.8, it never bothers to switch back to 192.168.1.12 if it ever comes back up.
Is this the greatest piece of software ever or what?
So how can you fix this?
Fortunately, systemd comes with a great tool for solving this problem called systemd-timer.
It’s like folks who built systemd anticipated this issue and built a tool to allow us to fix the problem by ourselves instead of forcing them to fix the buggy code. Are these the most considerate people in the world or what?
First create a file called resolved-fixer.timer
at
/etc/systemd/system
:
[Unit]
Description=Trigger resolved fixer service
[Timer]
OnBootSec=15m
OnUnitActiveSec=2m
Persistent=true
[Install]
WantedBy=timers.target
Then create a file called resolved-fixer.service
in the same directory:
[Unit]
Description=Fix resolved
[Service]
Type=simple
ExecStart=resolvectl enp3s0 192.168.1.12 1.1.1.1
Change enp3s0
to your own network interface and the DNS servers to ones you want.
Now run these commands:
systemctl daemon-reload
systemctl enable resolved-fixer.timer
systemctl start resolved-fixer.timer
From now on, systemd will automatically set the correct DNS servers every 2 minutes. There’s still a chance that resolved will set the DNS back to 8.8.8.8 (did Google bribe them or something?) but this issue will be solved at the next 2 minute time lapse.
Some of your smarties will argue that you can also use a cron job for that.
Listen, you have to fully embrace systemd or else you’ll be called a hater and receive death threats via email.
That’s why you need to use a timer and not cron.
© Josh Michael Karamuth 2022