How to run script in docker container with additional capabilities (docker exec … --cap-add …)

元气小坏坏 提交于 2021-01-29 09:21:47

问题


How can I run a script in a docker container with additional capabilities, such as NET_ADMIN?

I'm testing out some commands that I'd like to run in a docker image that require the NET_ADMIN permissions. For example, this works:

docker run --rm -it --cap-add 'NET_ADMIN' debian:stable-slim "iptables -L"

But if I want to execute a script (via docker exec), then suddenly the --cap-add option is not available.

root@disp8686:~# cat << EOF > docker_script.sh
> apt-get update
> apt-get -y install iptables
> iptables -L
> EOF
root@disp8686:~# docker exec -it --cap-add 'NET_ADMIN' debian:stable-slim docker_script.sh
unknown flag: --cap-add
See 'docker exec --help'.
root@disp8686:~# 

Why does --cap-add exist for docker run but not docker exec and how can I run a script in a docker container using --cap-add?


回答1:


docker exec does not support the --cap-add option, but you can use the --volume option of docker run to make a script on the docker host available to a container and execute it inside the container as follows:

tmpDir=`mktemp -d`
pushd "${tmpDir}"

cat << EOF > docker_script.sh
apt-get update
apt-get -y install iptables
iptables -L
EOF
chmod +x docker_script.sh

sudo docker run --rm -it --cap-add 'NET_ADMIN' --volume "${tmpDir}:/root" debian:stable-slim /bin/bash -c "cd /root && ./docker_script.sh"

Here is an example execution in Debian 10:

user@disp7086:~$ tmpDir=`mktemp -d`
user@disp7086:~$ pushd "${tmpDir}"
/tmp/tmp.PXmB9uJ8oM ~
user@disp7086:/tmp/tmp.PXmB9uJ8oM$ 
user@disp7086:/tmp/tmp.PXmB9uJ8oM$ cat << EOF > docker_script.sh
> apt-get update
> apt-get -y install iptables
> iptables -L
> EOF
user@disp7086:/tmp/tmp.PXmB9uJ8oM$ chmod +x docker_script.sh
user@disp7086:/tmp/tmp.PXmB9uJ8oM$ 

user@disp7086:/tmp/tmp.PXmB9uJ8oM$ sudo docker run --rm -it --cap-add 'NET_ADMIN' --volume "${tmpDir}:/root" debian:stable-slim /bin/bash -c "cd /root && ./docker_script.sh"
Get:1 http://deb.debian.org/debian stable InRelease [122 kB]
...
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
user@disp7086:/tmp/tmp.PXmB9uJ8oM$



来源:https://stackoverflow.com/questions/63959783/how-to-run-script-in-docker-container-with-additional-capabilities-docker-exec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!