The docker exec command

The docker exec command provides the much-needed help to users, who are deploying their own web servers or have other applications running in the background. Now, it is not necessary to log in to run the SSH daemon in the container.

  1. First, create a Docker container:
      $ sudo docker run --name trainingapp   
training/webapp:latest
Unable to find image
'training/webapp:latest' locally
latest: Pulling from training/webapp
9dd97ef58ce9: Pull complete
a4c1b0cb7af7: Pull complete
Digest: sha256:06e9c1983bd6d5db5fba376ccd63bfa529e8d02f23d5079b8f74a616308fb11d
Status: Downloaded newer image for
training/webapp:latest
  1. Next, run the docker ps -a command to get the container ID:
      $ sudo docker ps -a
a245253db38b training/webapp:latest
"python app.py"
  1. Then, run the docker exec command to log in to the container:
      $ sudo docker exec -it a245253db38b bash
root@a245253db38b:/opt/webapp#
  1. Note that the docker exec command can only access the running containers, so if the container stops functioning, then you need to restart the stopped container in order to proceed. The docker exec command spawns a new process in the target container using the Docker API and CLI. So if you run the ps -aef command inside the target container, it looks like this:
      # ps -aef
UID PID PPID C STIME TTY TIME
CMD
root 1 0 0 Nov 26 ? 00:00:53
python app.py
root 45 0 0 18:11 ? 00:00:00
bash
root 53 45 0 18:11 ? 00:00:00
ps -aef

Here, python app.y is the application that is already running in the target container, and the docker exec command has added the bash process inside the container. If you run kill -9 pid(45), you will be automatically logged out of the container.

If you are an enthusiastic developer, and you want to enhance the exec functionality, you can refer to https://github.com/chris-rock/docker-exec.

Using the docker exec command only for monitoring and diagnostic purposes is recommended, and I personally believe in the concept of one process per container, which is one of the best practices widely accentuated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset