如何进入 Docker 容器的外壳?

我开始使用 Docker。我正在使用 WordPress 基本映像和 docker-compose。

我正在尝试使用 ssh 进入其中一个容器,以检查在初始构建期间创建的文件 / 目录。我试图运行docker-compose run containername ls -la ,但是没有做任何事情。即使这样做,我还是希望有一个可以遍历目录结构的控制台,而不是运行单个命令。用 Docker 执行此操作的正确方法是什么?

答案

docker exec -it <mycontainer> bash
$ 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
$ docker exec -it d2d4a89aaee9 ip addr
$ docker exec -it web sh
/ # echo This is inside the container.
This is inside the container.
/ # exit
$
docker exec -t -i container_name /bin/bash
apt-get update
apt-get install openssh-server

mkdir /var/run/sshd
chmod 0755 /var/run/sshd
/usr/sbin/sshd

useradd --create-home --shell /bin/bash --groups sudo username ## includes 'sudo'
passwd username ## Enter a password

apt-get install x11-apps ## X11 demo applications (optional)
ifconfig | awk '/inet addr/{print substr($2,6)}' ## Display IP address (optional)
ssh -X username@IPADDRESS
xeyes ## run an X11 demo app in the client
$ docker-compose exec web bash
docker run -d -p 2222:22 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \
  jeroenpeeters/docker-ssh

ssh localhost -p 2222
winpty docker exec -it <container_id> sh
sudo docker exec -i -t (container ID) bash
docker exec -it 9f7d99aa6625 ash
docker exec -it 9f7d99aa6625 sh
docker exec -it d8c25fde2769 cmd
$ docker run --rm -it --entrypoint /bin/ash image_name
$ docker run --rm -it --entrypoint /bin/sh image_name
$ docker run --rm -it --entrypoint /bin/bash image_name