進入docker容器並執行命令的的3中方法
- docker exec
- nsenter
- docker attach "container"
建議使用nsenter, exec有時候會有問題。 attach執行完之后會自動退出
exec需要在運行中的容器中執行:
nsenter需要安裝,默認最小安裝里面有,yum -y install util-linux
attach需要是啟動的容器,退出的需要使用start先啟動- docker start CONTAINER(使用attach進入容器后退出后容器會退出)
[root@docker01 ~]# docker --help|grep exec
exec Run a command in a running container
[root@docker01 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
9218c822d3a5 docker.io/centos "/bin/bash" 11 hours ago Up 11 hours cent03
e4d5b979923b docker.io/centos "bash" 21 hours ago Up 11 hours cent02
fe7ab7cd9ec0 bash "docker-entrypoint..." 21 hours ago Up 12 hours cent01
216dc5feb799 8b89e48b5f15 "/bin/bash" 21 hours ago Up 12 hours 80/tcp nginx02
[root@docker01 ~]# docker exec cent01 route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default 172.17.0.1 0.0.0.0 UG 0 0 0 eth0
172.17.0.0 * 255.255.0.0 U 0 0 0 eth0
[root@docker01 ~]#
[root@docker01 scripts]# rpm -ql util-linux|grep nsenter
/usr/bin/nsenter
/usr/share/bash-completion/completions/nsenter
/usr/share/man/man1/nsenter.1.gz
[root@docker01 scripts]# rpm -ql util-linux|grep nsenter
exec直接進入bash的方法:
[root@docker01 work]# docker exec -it cent02 /bin/bash
[root@e4d5b979923b /]# cat /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.4 e4d5b979923b
直接去下載了httpd的容器並啟動80端口的httpd服務。
[root@docker01 scripts]# docker run -d -p 83:80 --name cent_80 httpd
Unable to find image 'httpd:latest' locally
Trying to pull repository docker.io/library/httpd ...
latest: Pulling from docker.io/library/httpd
d660b1f15b9b: Pull complete
aa1c79a2fa37: Pull complete
f5f6514c0aff: Pull complete
676d3dd26040: Pull complete
4fdddf845a1b: Pull complete
28ecdadc5f88: Pull complete
5d882098e42b: Pull complete
Digest: sha256:2edbf09d0dbdf2a3e21e4cb52f3385ad916c01dc2528868bc3499111cc54e937
Status: Downloaded newer image for docker.io/httpd:latest
c720d0aa41860f2d88cd652f395d52279f0a485b7852da5d7fce4627ac7ef816
[root@docker01 scripts]# curl 10.0.0.181:83
<html><body><h1>It works!</h1></body></html>