进入docker容器并执行命令的的3中方法

进入docker容器并执行命令的的3中方法

 

  1. docker exec
     
  2. nsenter
     
  3. 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>

posted @ 2019-02-14 17:10  Davidge大卫哥博客  阅读(995)  评论(0编辑  收藏  举报