May 22, 2021 Docker From entry to practice
When using
-d
parameter, the container starts and goes into the background.
There are a number of ways to get into the container at some point, including
docker attach
command
nsenter
tool.
docker attach
Docker's own command.
Here's an example of how to use the command.
$ sudo docker run -idt ubuntu
243c32535da7d142fb0e6df616a3c3ada0b8ab417937c853a9e1c251f499f550
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
243c32535da7 ubuntu:latest "/bin/bash" 18 seconds ago Up 17 seconds nostalgic_hypatia
$sudo docker attach nostalgic_hypatia
root@243c32535da7:/#
However,
attach
command is sometimes inconvenient. W
hen multiple windows are attached to the same container at the same time, all windows are displayed synchronously.
When one window is blocked by a command, other windows cannot do anything else.
nsenter
tool is included after version 2.23 of the util-linux package.
If the util-linux package does not have this command in the system, you can install it from the source as follows.
$ cd /tmp; curl https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz | tar -zxf-; cd util-linux-2.24;
$ ./configure --without-ncurses
$ make nsenter && sudo cp nsenter /usr/local/bin
nsenter
access the namespace of another process. T
he root permission is required for nsenter to function properly. U
nfortunately, Ubuntu 14.04 still uses util-linux 2.20.
To install the latest version of util-linux (2.24), follow these steps:
$ wget https://www.kernel.org/pub/linux/utils/util-linux/v2.24/util-linux-2.24.tar.gz; tar xzvf util-linux-2.24.tar.gz
$ cd util-linux-2.24
$ ./configure --without-ncurses && make nsenter
$ sudo cp nsenter /usr/local/bin
In order to connect to the container, you also need to find the PID of the container's first process, which can be obtained through the following command.
PID=$(docker inspect --format "{{ .State.Pid }}" <container>)
With this PID, you can connect to this container:
$ nsenter --target $PID --mount --uts --ipc --net --pid
Here's a complete example.
$ sudo docker run -idt ubuntu
243c32535da7d142fb0e6df616a3c3ada0b8ab417937c853a9e1c251f499f550
$ sudo docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
243c32535da7 ubuntu:latest "/bin/bash" 18 seconds ago Up 17 seconds nostalgic_hypatia
$ PID=$(docker-pid 243c32535da7)
10981
$ sudo nsenter --target 10981 --mount --uts --ipc --net --pid
root@243c32535da7:/#
Easier, we recommend that you .bashrc_docker and put the content in .bashrc.
$ wget -P ~ https://github.com/yeasy/docker_practice/raw/master/_local/.bashrc_docker;
$ echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc; source ~/.bashrc
This file defines a number of commands that are convenient for docker, such as
docker-pid
to get the PID of a container, and
docker-enter
enter the container or execute commands directly inside the container.
$ echo $(docker-pid <container>)
$ docker-enter <container> ls