docker tutorials

How to run a command in a running docker container ?

This tutorial guides you on how to run a command in a running docker container. Let’s use the standard ubuntu container image for our exercise.

Run a command in a running docker container

Docker provides docker exec command which can be used for running a new command in a running docker container. Note, the command started using docker exec command runs only while the docker container is already running. For example, let’s say you are using docker exec command for the docker container which is not running as shown below.

$ docker run --name ubuntu_bash ubuntu

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
3e8459f6afa8        ubuntu              "/bin/bash"         5 seconds ago       Exited (0) 4 seconds ago                       ubuntu_bash

$ docker exec -d ubuntu_bash echo "Hello!"

Error response from daemon: Container 3e8459f6afa876f3716e98062de172e164a70def2d8f703b07d2c7a6e20269dd is not running

First, start the docker container using the following command, this will create a new docker container named ubuntu_bash and start a bash session as shown below. You can try echo statement and keep that bash session alive in one terminal.

Terminal 1

$ docker run --name ubuntu_bash --rm -it ubuntu bash
root@13ead6ef1669:/# echo Hello
Hello

Open another terminal (terminal 2) and try running docker ps command to check whether container named ubuntu_bash is up and running as shown below.

Terminal 2

$ docker ps -a

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
13ead6ef1669        ubuntu              "bash"              47 seconds ago      Up 46 seconds                           ubuntu_bash

In terminal 2, now execute the following docker exec command on the ubuntu_bash (running container). This command will create a new file called execDemo under tmp directory inside the running container as shown below.

$ docker exec -d ubuntu_bash touch tmp/execDemo

Now, in the terminal 1 you already have an interactive bash shell on the running container, go there and try to list files as shown below to verify the new file that was created using the docker exec command on the running container.

$ docker run --name ubuntu_bash --rm -it ubuntu bash
root@13ead6ef1669:/# echo Hello
Hello
------------- Done in Previous Step -------------------

<Try the following in terminal 1 to verify>

root@13ead6ef1669:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@13ead6ef1669:/# cd tmp
root@13ead6ef1669:/tmp# ls
execDemo

That’s it. Now you are able to run a command in a running docker container. Hope this helped 🙂

Also See:

References:

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments