docker exec Executes Multiple Command Operations

  • 2021-10-25 08:19:56
  • OfStack

The docker exec command executes commands in a running container.

The format of the docker exec command is:


docker exec [OPTIONS] container_name COMMAND [ARG...]

OPTIONS Description:

-d, which executes the command in the background mode;

-e, setting environment variables

-i, interactive mode

-t, set TTY

-u, user name or UID, for example myuser: myusergroup

Usually COMMAND can only be one statement. In order to support the execution of multiple commands, it is necessary to connect multiple commands to Shell.

An example of the use of the docker exec command is as follows:


sudo docker exec myContainer bash -c "cd /home/myuser/myproject && git fetch ssh://gerrit_server:29418/myparent/myproject ${GERRIT_REFSPEC} && git checkout FETCH_HEAD";
sudo docker exec myContainer bash -c "cd /home/myuser/myproject;git fetch ssh://gerrit_server:29418/myparent/myproject ${GERRIT_REFSPEC};git checkout FETCH_HEAD";

Note: For paused or stopped containers, the docker exec command cannot be executed. The following exception will be thrown:


docker pause myContainer 
docker exec myContainer ...

Supplement: Docker exec Host Executes Command on Container

Under Docker, exec performs naming operations on containers from hosts


docker exec -it 
#  Interaction can enter the container  ; exec  You can also execute commands on the container on the host machine; 
docker attach 
#  You can also enter the container 

1. Execute commands remotely: File operation:


docker exec -d nginx1 touch /etc/1.txt
-d Backstage type, in  nginx1  Container to create 1 A  1.txt  Documents 

2. The file operation copy is still cp;;


docker cp 1.11.sh nginx1:/root/
#  Slave host   Copy a file 
docker exec nginx1 ls /root
#  View   Documents 
docker exec nginx1 rm -rf /root/1.11.sh
#  Delete a file 

3. diff views the directory structure of the container;


docker diff nginx1
#  View  nginx1  File structure of container 

Related articles: