As Michael Sun stated in his answer
docker exec executes a new command / creates a new process in the container environment, while docker attach simply connects the standard input / output / error of the main process (with PID 1) inside the container with the corresponding standard input / output / current error terminal (terminal that you use to run the command).
My answer will focus on allowing you to confirm the above statement and understand it more clearly.
Open a terminal window and run the command docker run -itd --name busybox busybox/bin/sh . The busybox command image busybox if it is not already. He will then create a container named busybox using this image.
You can check the status of your container by running docker ps -a | grep busybox docker ps -a | grep busybox docker ps -a | grep busybox docker ps -a | grep busybox .
If you run docker top busybox , you should see something like this.
UID PID PPID C STIME TTY TIME CMD root 7469 7451 0 11:40 pts/0 00:00:00 /bin/sh
Of course, PID , PPID and other values ββwill be different in your case. You can use other tools and utilities such as pstree , top , htop to see a list of PID and PPID .
PID and PPID mean process identifier and parent process identifier. The process started when we created and launched our container using the /bin/sh command. Now run the docker attach busybox . This will attach the standard container I / O / error stream to your terminal.
After attaching the container, create a shell session by running the sh command. Press CTRL-p CTRL-q sequence. This will disconnect the terminal from the container and keep it operational. If you now run docker top busybox , you should see two processes in the list.
UID PID PPID C STIME TTY TIME CMD root 7469 7451 0 11:40 pts/0 00:00:00 /bin/sh root 7737 7469 0 11:43 pts/0 00:00:00 sh
But the PPID two processes will be different. In fact, the PPID second process will be the same as the PID first. The first process acts as the parent process for the shell session we just created.
Now run docker exec -it busybox sh . Once inside the container, check the list of running processes for the busybox container in another terminal window by running the docker top busybox . You should see something like this.
UID PID PPID C STIME TTY TIME CMD root 7469 7451 0 11:40 pts/0 00:00:00 /bin/sh root 7737 7469 0 11:43 pts/0 00:00:00 sh root 7880 7451 0 11:45 pts/1 00:00:00 sh
PPID first and third processes will be the same, which confirms that docker exec creates a new process in the container environment, while docker attach simply connects the standard input / output / error of the main process inside the container with the corresponding standard input / output / error of the current terminal.