docker进入容器的几种方法

运行时进入

一 启动进入容器指定bash 退出后容器关闭

[root@Centos-node3 ~]# docker run -it centos bash
[root@83c6b25aca09 /]# 

docker attach

docker attach进入容器后退出 如果容器没有指定bash环境会停留在空白页面 退出后容器也会正常退出(进入容器后其他人进入容器可以看到你输入的信息)

[root@Centos-node3 ~]# docker run -it -d --name mynginx nginx /bin/bash
c23ba383b76baa6c3e1a9450e23e6e4f46724a4e2b8e8c2b8c002e54ba2e5f32
[root@Centos-node3 ~]# docker attach mynginx
root@c23ba383b76b:/# ls
bin   dev  home  lib64    mnt  proc  run     srv  tmp  var
boot  etc  lib     media    opt  root  sbin  sys  usr
root@c23ba383b76b:/# exit
exit
[root@Centos-node3 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

docker exec

docker exec 进入容器 会启用一个bash环境

[root@Centos-node3 ~]# docker run -it -d --name mycentos centos /bin/bash
68e1f711a4990f66ad3456b453591c3fa9a7d22d4fed3e50bda1cf27a36cc60a
[root@Centos-node3 ~]# docker exec -it mycentos bash
[root@68e1f711a499 /]# ps -ef
   PID TTY          TIME CMD
     1 ?        00:00:00 bash
    13 ?        00:00:00 bash
    25 ?        00:00:00 ps
[root@68e1f711a499 /]# exit  
exit
[root@Centos-node3 ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED              STATUS              PORTS               NAMES
68e1f711a499        centos              "/bin/bash"         About a minute ago   Up About a minute                       mycentos
c23ba383b76b        nginx               "/bin/bash"         5 minutes ago        Up 2 minutes        80/tcp              mynginx

[root@Centos-node3 ~]# docker exec -it mycentos ls
anaconda-post.log dev home lib64 mnt proc run srv tmp var
bin etc lib media opt root sbin sys usr

nsenter

yum -y install util-linux                         #安装nsenter命令

[root@Centos-node3 ~]# docker inspect -f "{{ .State.Pid }}" mycentos
30428                                              #查看容器pid

nsenter -t 30428 -m -u -i -n -p 
-t:指定PID
–u:参数是进入到uts namespace中 
–i:参数是进入到System V IPC namaspace中 
–n:参数是进入到network namespace中 
–p:参数是进入到pid namespace中

自定义脚本

脚本方式进入(可直接传参docker name 或者ID)

[root@Centos-node2 ~]# cat docker_in.sh 
#!/bin/bash

#Use nsenter to access docker

docker_in(){
    NAME_ID=$1
    PID=$(docker inspect -f "{{ .State.Pid }}" $NAME_ID)
    nsenter -t $PID -m -u -i -n -p
}

docker_in $1

 

posted @ 2018-08-09 23:48  闫世成  阅读(29422)  评论(0编辑  收藏  举报