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
[email protected]:/# 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
[email protected]:/# echo Hello
Hello
------------- Done in Previous Step -------------------

<Try the following in terminal 1 to verify>

[email protected]:/# ls
bin  boot  dev  etc  home  lib  lib32  lib64  libx32  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[email protected]:/# cd tmp
[email protected]:/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:

Leave a Reply

avatar
  Subscribe  
Notify of