I want to create a new namespace with a different /etc/hosts
, so I tried to use mount --bind
with unshare to create it as referenced in this answer: https://unix.stackexchange.com/a/242830/271204
# Create temp hosts
export TEMP_HOSTS=$(mktemp XXXXXXX.hosts)
trap "{ rm -f $TEMP_HOSTS; }" EXIT
cat /etc/hosts > $TEMP_HOSTS
Create new ns
unshare -m bash
mount --make-private "$TEMP_HOSTS" /etc/hosts --bind
Then I got a new shell (denoted as Shell2), and wrote something to it. It's ok and /etc/hosts
is still in mount after append or edit.
(Shell2) # cat /proc/self/mountinfo | grep /etc/hosts
218 189 8:1 /tmp/Z3flEXS.hosts /etc/hosts rw,relatime - ext4 /dev/sda1 rw,errors=remount-ro
(Shell2) # echo '127.0.0.1 aaaa' >> /etc/hosts
(Shell2) # cat /proc/self/mountinfo | grep /etc/hosts
218 189 8:1 /tmp/Z3flEXS.hosts /etc/hosts rw,relatime - ext4 /dev/sda1 rw,errors=remount-ro
When I start a new terminal window or create or new ssh session, I get a shell with old namespace of the system and denote it as Shell1.
The /etc/hosts under Shell1 is still the old version as expect because the mount is --make-private
. But when I modify the /etc/hosts under Shell1 with `vim, /etc/hosts under Shell2 is also changed and the mount is disappeared.
# Append "127.0.0.1 aaaaa" with vim, or you can use vim interactively.
(Shell1) # vim -c "$ s/$/\r127.0.0.1 aaaaa/" -c "wq" /etc/hosts
(Shell1) # md5sum /etc/hosts
1580e29f05e6af70012afe37ce08cb5a /etc/hosts
(Shell2) # cat /proc/self/mountinfo | grep /etc/hosts
* Nothing here
(Shell2) # md5sum /etc/hosts
1580e29f05e6af70012afe37ce08cb5a /etc/hosts
But in the step of modifying /etc/hosts in shell1, /etc/hosts
in new namespace will not be affected when I use echo '127.0.0.1 aaaa' >> /etc/hosts
instead of using vim
to edit and save.
So my question is why I modified file with vim
in old namespace, the file in the new namespace is also been affected? Why the behavior is different when using shell redirection? Can I change unshare
or mount
options to avoid the change caused by vim in old namespace?