The Ephemeral Cache
Modern Ubuntu installations use systemd-resolved as the default service for local DNS resolution and caching. When you visit a website or ping a server, Ubuntu stores the IP address mapping in this cache so subsequent requests are much faster. However, systemd-resolved is designed to be highly dynamic. It automatically flushes or empties its DNS cache during certain network events, such as when your network interface goes down and comes back up, when you switch from Wi-Fi to Ethernet, or when you connect to a VPN. While this ensures you don’t get stuck with stale DNS records from an old network, it can be frustrating if you are developing locally or testing DNS configurations and want the cache to persist regardless of network state changes.
Overriding systemd-resolved Behavior
To enforce persistence and stop Ubuntu from automatically emptying the DNS cache when your network state changes, you must reconfigure the systemd-resolved service.
This requires editing a system configuration file via the terminal. Open a terminal (Ctrl+Alt+T). Type the following command to open the resolved configuration file with administrative privileges: sudo nano /etc/systemd/resolved.conf. Enter your password. Scroll through the file using your arrow keys until you find the [Resolve] section. Look for the line that says Cache=. It might be commented out with a hash (#) symbol. If it says Cache=yes, this is the default behavior (caching is on, but flushes on network changes). To force it to hold the cache aggressively, change the line to read Cache=no-negative (which caches successful lookups persistently but not failures) or simply leave it as Cache=yes but you must stop the NetworkManager from sending flush signals. A more robust way to prevent the flush without breaking systemd is to restart the service manually when needed: save the file (Ctrl+O, Enter, Ctrl+X) and run sudo systemctl restart systemd-resolved.