Execute a command inside Docker container

Published: December 02, 2022

Last updated: December 02, 2022

Execute a command inside Docker container

In this article, we cover how to execute a command inside Docker container. We have already seen in previous article, how to Connect to a Shell inside Docker container. Therein, we used two options i.e. -i and -t to connect to the shell.

docker container run -i -t <container-image>

where, -i or the interactive option was used to keep standard input (STDIN) open and,

-t is used to allocate a Pseudo-TTY.

What we are about to cover would require a running Docker container. We cover this in detail next.

Execute a command inside a Docker container

I. To execute a command inside a Docker container, use the following syntax -

docker container exec [OPTIONS] <container_NAME/ID> {command}

For instance, for container name - ABC and command to execute - ls -l;

docker container exec ABC ls -l

At this stage, it would return with -

Error response from daemon: Container ... is not running

Clearly, we haven't started our container yet. So, to start a Docker container -

docker container start <container-NAME/ID>

For instance,

docker container start ABC

This time around, if we try to execute the command again it would work fine.

docker container exec ABC ls -l

II. To get the command to execute from a specific directory, use -w option -

docker container exec -i -t -w /dev/shm ABC /bin/bash

III. To set environment variables, use -e option. For instance, declare a variable PR with values - "Test Output". Then, run it from containers' SHELL.

docker container exec -i -t -e PR="Test Output" ABC /bin/bash

And, run the following command in the containers' SHELL to see what's stored in variable PR -

echo $PR

In conclusion, we have covered how to execute a command inside a Docker container.

Additional Info -

There are times when we want the access to a Shell through above command. For instance,

docker container exec ABC /bin/sh

But, things don't move anywhere. So, to access /bin/sh, use -i and -t options.

docker container exec -i -t ABC /bin/sh

To exit the Docker containers' Shell, either use Ctrl+D or enter the following in terminal -

exit

Use the following to get the Container Name, ID and present status of a Docker container -

docker container ls -a

where, -a is for all the containers irrespective of their STATUS.