program tip

Docker 컨테이너의 셸에 어떻게 들어가나요?

radiobox 2020. 9. 28. 08:50
반응형

Docker 컨테이너의 셸에 어떻게 들어가나요?


Docker 작업을 시작하고 있습니다. WordPress 기본 이미지와 docker-compose를 사용하고 있습니다.

초기 빌드 중에 생성 된 파일 / 디렉터리를 검사하기 위해 컨테이너 중 하나에 ssh를 시도하고 있습니다. 를 실행하려고했지만 docker-compose run containername ls -la아무 일도하지 않았습니다. 그렇게하더라도 단일 명령을 실행하는 것보다 디렉토리 구조를 탐색 할 수있는 콘솔이 필요합니다. Docker로이를 수행하는 올바른 방법은 무엇입니까?


docker attachDocker 컨테이너에 연결할 수 있지만 실제로 ssh. 예를 들어 컨테이너가 웹 서버를 실행하는 경우 웹 서버 프로세스 docker attach표준 출력연결할 수 있습니다 . 반드시 껍질을 제공하지는 않습니다.

docker exec명령은 당신이 찾고있는 무엇 아마; 이렇게하면 기존 컨테이너 내에서 임의의 명령을 실행할 수 있습니다. 예를 들면 :

docker exec -it <mycontainer> bash

물론 실행중인 명령은 컨테이너 파일 시스템에 있어야합니다.

위의 명령 <mycontainer>에서 대상 컨테이너의 이름 또는 ID입니다. 사용 여부는 중요하지 않습니다 docker compose. 실행 docker ps하고 ID (첫 번째 열에 표시되는 16 진수 문자열) 또는 이름 (마지막 열에 표시됨)을 사용하십시오. 예 :

$ 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
$

실행중인 컨테이너로 bash하려면 다음을 입력하십시오.

docker exec -t -i container_name /bin/bash

자신의 이유 때문에 SSH를 사용하고 싶다고 가정 해 보겠습니다. 몇 단계 만 거치면 할 수 있습니다. 설정을 위해 컨테이너 내부에서 실행하는 명령은 다음과 같습니다.

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 클라이언트로의 X11 포워딩을 사용하여 그래픽 애플리케이션 (컨테이너에 설치된 경우)을 실행할 수도 있습니다.

ssh -X username@IPADDRESS
xeyes ## run an X11 demo app in the client

다음은 몇 가지 관련 리소스입니다.


알림 :이 답변은 내가 작성한 도구를 홍보합니다.

실행중인 모든 컨테이너에 '고정'할 수있는 컨테이너화 된 SSH 서버를 만들었습니다. 이렇게하면 모든 컨테이너로 컴포지션을 만들 수 있습니다. 유일한 요구 사항은 컨테이너에 Bash가 있다는 것입니다.

다음 예제는 이름이 'my-container'인 컨테이너에 연결된 SSH 서버를 시작합니다.

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

이 SSH 서비스에 연결하면 (선택한 SSH 클라이언트를 사용하여) Bash 세션이 'my-container'라는 이름의 컨테이너에서 시작됩니다.

더 많은 포인터 및 문서는 https://github.com/jeroenpeeters/docker-ssh를 참조하십시오.


여기에서 저와 같은 Docker Compose 관련 답변을 찾고 있다면 생성 된 컨테이너 ID를 조회 할 필요없이 쉬운 방법을 제공합니다.

docker-compose execdocker-compose.yml파일 에 따라 서비스 이름을 사용 합니다.

따라서 '웹'서비스에 대한 Bash 셸을 얻으려면 다음을 수행 할 수 있습니다.

$ docker-compose exec web bash

Windows에서 Docker를 사용 중이고 컨테이너에 대한 셸 액세스 권한을 얻으려면 다음을 사용하십시오.

winpty docker exec -it <container_id> sh

아마도 이미 Git Bash가 설치되어있을 것입니다. 그렇지 않은 경우 설치하십시오.


다음 명령을 사용하여 SSH를 Docker 컨테이너에 연결합니다.

sudo docker exec -i -t (container ID) bash

어떤 경우에는 이미지가 알파인 기반 일 수 있습니다. 이 경우 다음을 던집니다.

OCI 런타임 exec 실패 : exec 실패 : container_linux.go : 348 : 컨테이너 프로세스 시작으로 인해 "exec : \"bash \ ": $ PATH에서 실행 파일을 찾을 수 없음": 알 수 없음

때문에 /bin/bash존재하지 않습니다. 대신 다음을 사용해야합니다.

docker exec -it 9f7d99aa6625 ash

또는

docker exec -it 9f7d99aa6625 sh

Windows 컨테이너의 cmd에 연결하려면 다음을 사용하십시오.

docker exec -it d8c25fde2769 cmd

여기서 d8c25fde2769 는 컨테이너 ID입니다.


컨테이너가 이미 종료 된 경우 (오류로 인한 것일 수 있음) 다음을 수행 할 수 있습니다.

$ 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

새 컨테이너를 만들고 그 안에 셸을 가져옵니다. --rm을 지정 했으므로 셸을 종료하면 컨테이너가 삭제됩니다.


간단합니다 !

모든 Docker 이미지를 나열하십시오.

sudo docker images

내 시스템에서 다음 출력이 표시되었습니다.

REPOSITORY          TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
bash                latest              922b9cc3ea5e        9 hours ago
14.03 MB
ubuntu              latest              7feff7652c69        5 weeks ago         81.15 MB

내 PC에 두 개의 Docker 이미지가 있습니다. 첫 번째를 실행하고 싶다고 가정 해 보겠습니다.

sudo docker run -i -t ubuntu:latest /bin/bash

이것은 컨테이너의 터미널 제어를 제공합니다. 이제 컨테이너 내에서 모든 유형의 셸 작업을 수행 할 수 있습니다. 이렇게 ls하면 파일 시스템의 루트에있는 모든 폴더가 출력됩니다.

bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

GOINSIDE 솔루션

다음을 사용하여 goinside명령 줄 도구를 설치합니다 .

sudo npm install -g goinside

다음을 사용하여 적절한 터미널 크기로 도커 컨테이너 내부로 이동하십시오.

goinside docker_container_name

오래된 대답

이 스 니펫을 ~/.profile다음 위치에 넣었습니다 .

goinside(){
    docker exec -it $1 bash -c "stty cols $COLUMNS rows $LINES && bash";
}
export -f goinside

Not only does this make everyone able to get inside a running container with:

goinside containername

It also solves a long lived problem about fixed Docker container terminal sizes. Which is very annoying if you face it.

Also if you follow the link you'll have command completion for your docker container names too.


Use:

docker attach <container name/id here>

The other way, albeit there is a danger to it, is to use attach, but if you Ctrl + C to exit the session, you will also stop the container. If you just want to see what is happening, use docker logs -f.

:~$ docker attach --help
Usage:  docker attach [OPTIONS] CONTAINER

Attach to a running container

Options:
      --detach-keys string   Override the key sequence for detaching a container
      --help                 Print usage
      --no-stdin             Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)

Use this command:

docker exec -it containerid /bin/bash

docker exec will definitely be a solution. An easy way to work with the question you asked is by mounting the directory inside Docker to the local system's directory.

So that you can view the changes in local path instantly.

docker run -v /Users/<path>:/<container path> 

To inspect files, run docker run -it <image> /bin/bash to get an interactive terminal. The list of images can be obtained by docker images. In contrary to docker exec this solution works also in case when an image doesn't start (or quits immediately after running).


If you have Docker installed with Kitematic, you can use the GUI. Open Kitematic from the Docker icon and in the Kitematic window select your container, and then click on the exec icon.

You can see the container log and lots of container information (in settings tab) in this GUI too.

Select Kitematic from menu

Click on exec


I've created a terminal function for easier access to the container's terminal. Maybe it's useful to you guys as well:

So the result is, instead of typing:

docker exec -it [container_id] /bin/bash

you'll write:

dbash [container_id]

Put the following in your ~/.bash_profile (or whatever else that works for you), then open a new terminal window and enjoy the shortcut:

#usage: dbash [container_id]
dbash() {
    docker exec -it "$1" /bin/bash
}

you can interact with the terminal in docker container by passing the option -ti

docker run --rm -ti <image-name>
eg: docker run --rm -ti ubuntu

-t stands for terminal -i stands for interactive


$ docker exec -it <Container-Id> /bin/bash

Or depending on the shell, it can be

$ docker exec -it <Container-Id> /bin/sh

You can get the container-Id via docker ps command

-i = interactive

-t = to allocate a psuedo-TTY


In my case, for some reason(s) I need to check all the network involved information in each container. So the following commands must be valid in a container...

ip
route
netstat
ps
...

I checked through all these answers, none were helpful for me. I’ve searched information in other websites. I won’t add a super link here, since it’s not written in English. So I just put up this post with a summary solution for people who have the same requirements as me.

Say you have one running container named light-test. Follow the steps below.

  • docker inspect light-test -f {{.NetworkSettings.SandboxKey}}. This command will get reply like /var/run/docker/netns/xxxx.
  • Then ln -s /var/run/docker/netns/xxxx /var/run/netns/xxxx. The directory may not exist, do mkdir /var/run/netns first.
  • Now you may execute ip netns exec xxxx ip addr show to explore network world in container.

PS. xxxx is always the same value received from the first command. And of course, any other commands are valid, i.e. ip netns exec xxxx netstat -antp|grep 8080.


Another option is to use nsenter.

PID=$(docker inspect --format {{.State.Pid}} <container_name_or_ID>)
nsenter --target $PID --mount --uts --ipc --net --pid

If you are using Docker Compose then this will take you inside a Docker container.

docker-compose run container_name /bin/bash

Inside the container it will take you to WORKDIR defined in the Dockerfile. You can change your work directory by

WORKDIR directory_path # E.g  /usr/src -> container's path

For docker-compose up (Docker4Drupal)

docker-compose exec php bash

I use Docker for Drupal on a Linux laptop. After running the container I use 'docker-compose exec php bash' to connect with the container so I can run drush commandos. It works fine for me.

참고URL : https://stackoverflow.com/questions/30172605/how-do-i-get-into-a-docker-containers-shell

반응형