Docker exec 命令用来在宿主机直接在容器内部运行一个命令,不需要进入到容器。帮助信息如下:
[root@localhost ~]# docker exec --help Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...] Run a command in a running container Options: -d, --detach Detached mode: run command in the background --detach-keys string Override the key sequence for detaching a container -e, --env list Set environment variables -i, --interactive Keep STDIN open even if not attached --privileged Give extended privileges to the command -t, --tty Allocate a pseudo-TTY -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) -w, --workdir string Working directory inside the container
其中:
--detach-keys string 覆盖用于分离容器的键序列
-e, --env list 设置环境变量
-i, --interactive 保持STDIN打开,即使没有连接
--privileged 为该命令授予扩展特权
-t, --tty 分配一个pseudo-TTY
-u, --user string 用户名或UID (格式: <name|uid>[:<group|gid>])
-w, --workdir string 容器内的工作目录
实例:在容器中执行“ls”和“uname -r”命令。如下:
[root@localhost ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ba0b159d7a9a ubuntu "/bin/bash" 8 seconds ago Up 6 seconds unruffled_yalow [root@localhost ~]# docker exec -t ba0b159d7a9a ls bin dev home lib64 mnt proc run srv tmp var boot etc lib media opt root sbin sys usr [root@localhost ~]# docker exec -t ba0b159d7a9a uname -r 3.10.0-957.21.3.el7.x86_64
上图中,“docker exec -t ba0b159d7a9a ls”和“docker exec -t ba0b159d7a9a uname -r”命令是在容器 ba0b159d7a9a 中运行“ls”和“uname -r”命令。