Assign DNS to one particular process on Linux
Overview
Linux itself can only configure system-wide DNS by /etc/resolv.conf
. Here is a way to individually set DNS for a specific process, through the mount namespace without root. You only need a simple command if use a script.
Method
-
Bubblewrap is an unprivileged (root-free) container tool. We use
bwrap
command to use it to create a mount namespace so that the process under this namespace the see/etc/resolv.conf
content overwritten by us. -
Some programs will use the DNS cache provided by the system (usually provided by nscd), so the mount namespace needs to prevent the DNS cache from being accessed. Bannning
/var/run/nscd/
will do it.
Usage
Go to my Github repository to get the script
1proxc -d 5.5.5.5 -c nslookup my-website-with-cdn.com
2proxc -d 5.5.5.5 -c firefox http://my-website-with-cdn.com
3proxc -d 5.5.5.5 -c curl -v http://my-website-with-cdn.com
Only a simple command is needed to use this script.
Limitation
-
Due to the limitations of Bubblewrap, if processes outside the mount namespace delete, recreate or change
/etc/resolv.conf
, in the namespace/etc/resolv.conf
is also modified.Therefore, after NetworkManager switches the network, the DNS set by this method may become invalid. Alternatively we can disable NetworkManager writing
/etc/resolv.conf
. -
In containers such as bubblewrap, some programs using mount and namespace won't work, such as AppImage.
Buy me a coffee
Your donation will be an impetus for me!