Can not add new user in docker container with moun

2019-05-15 01:54发布

问题:

Example of the problem:

docker run -ti -v my_passwd:/etc/passwd -v my_shadow:/etc/shadow --rm centos
[root@681a5489f3b0 /]# useradd test # does not work !?
useradd: failure while writing changes to /etc/passwd
[root@681a5489f3b0 /]# ll /etc/passwd /etc/shadow # permission check
-rw-r--r-- 1 root root 157 Oct  8 10:17 /etc/passwd
-rw-r----- 1 root root 100 Oct  7 18:02 /etc/shadow

The similar problem arises when using passwd:

[root@681a5489f3b0 /]# passwd test
Changing password for user test.
New password: 
BAD PASSWORD: The password is shorter than 8 characters
Retype new password: 
passwd: Authentication token manipulation error

I have tried using the ubuntu image, but the same problem arises.

I can manually edit passwd file and shadow file from within container.

I am getting the same problem on following two machines:

Host OS: CentOS 7 - SELinux Disabled
Docker Version: 1.8.2, build 0a8c2e3

Host OS: CoreOS 766.4.0
Docker version: 1.7.1, build df2f73d-dirty

I've also opened issue on GitHub: https://github.com/docker/docker/issues/16857

回答1:

It's failing because passwd manipulates a temporary file, and then attempts to rename it to /etc/shadow. This fails because /etc/shadow is a mountpoint -- which cannot be replaced -- which results in this error (captured using strace):

102   rename("/etc/nshadow", "/etc/shadow") = -1 EBUSY (Device or resource busy)

You can reproduce this trivially from the command line:

# cd /etc
# touch foo
# mv foo shadow
mv: cannot move 'foo' to 'shadow': Device or resource busy

You could work around this by mounting a directory containing my_shadow and my_passwd somewhere else, and then symlinking /etc/passwd and /etc/shadow in the container appropriately:

$ docker run -it --rm -v $PWD/my_etc:/my_etc centos
[root@afbc739f588c /]# ln -sf /my_etc/my_passwd /etc/passwd
[root@afbc739f588c /]# ln -sf /my_etc/my_shadow /etc/shadow
[root@afbc739f588c /]# ls -l /etc/{shadow,passwd}
lrwxrwxrwx. 1 root root 17 Oct  8 17:48 /etc/passwd -> /my_etc/my_passwd
lrwxrwxrwx. 1 root root 17 Oct  8 17:48 /etc/shadow -> /my_etc/my_shadow
[root@afbc739f588c /]# passwd root
Changing password for user root.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@afbc739f588c /]#