如何进入 Docker 容器的外壳? [英] How do I get into a Docker container's shell?
问题描述
我开始使用 Docker.我正在使用 WordPress 基础映像和 docker-compose.
I'm getting started working with Docker. I'm using the WordPress base image and docker-compose.
我正在尝试通过 ssh 进入其中一个容器以检查在初始构建期间创建的文件/目录.我试图运行 docker-compose run containername ls -la
,但这没有做任何事情.即使有,我也宁愿有一个可以遍历目录结构的控制台,而不是运行单个命令.使用 Docker 执行此操作的正确方法是什么?
I'm trying to ssh into one of the containers to inspect the files/directories that were created during the initial build. I tried to run docker-compose run containername ls -la
, but that didn't do anything. Even if it did, I'd rather have a console where I can traverse the directory structure, rather than run a single command. What is the right way to do this with Docker?
推荐答案
docker attach
将让你连接到你的 Docker 容器,但这与 ssh<并不是一回事/代码>.例如,如果您的容器正在运行网络服务器,
docker attach
可能会将您连接到网络服务器进程的 stdout.它不一定会给你一个外壳.
docker attach
will let you connect to your Docker container, but this isn't really the same thing as ssh
. If your container is running a webserver, for example, docker attach
will probably connect you to the stdout of the web server process. It won't necessarily give you a shell.
docker exec
命令可能就是你要找的;这将允许您在现有容器内运行任意命令.例如:
The docker exec
command is probably what you are looking for; this will let you run arbitrary commands inside an existing container. For example:
docker exec -it <mycontainer> bash
当然,您运行的任何命令都必须存在于容器文件系统中.
Of course, whatever command you are running must exist in the container filesystem.
在上面的命令中,
是目标容器的名称或 ID.是否使用 docker compose
并不重要;只需运行 docker ps
并使用 ID(显示在第一列中的十六进制字符串)或名称(显示在最后一列中).例如,给定:
In the above command <mycontainer>
is the name or ID of the target container. It doesn't matter whether or not you're using docker compose
; just run docker ps
and use either the ID (a hexadecimal string displayed in the first column) or the name (displayed in the final column). E.g., given:
$ docker ps
d2d4a89aaee9 larsks/mini-httpd "mini_httpd -d /cont 7 days ago Up 7 days web
我可以跑:
$ docker exec -it web ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
18: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 02:42:ac:11:00:03 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.3/16 scope global eth0
valid_lft forever preferred_lft forever
inet6 fe80::42:acff:fe11:3/64 scope link
valid_lft forever preferred_lft forever
我可以通过运行来完成同样的事情:
I could accomplish the same thing by running:
$ docker exec -it d2d4a89aaee9 ip addr
同样,我可以在容器中启动一个shell;
Similarly, I could start a shell in the container;
$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$
这篇关于如何进入 Docker 容器的外壳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!