A docker container is an isolated environment that usually contains a single application with all required dependencies. Many times we need to run some commands inside a docker container. There are several ways in which we can execute a command inside a container and get the required output. Let’s see how we can do it.

Using Interactive Shell

We can directly access the shell of a container and execute our commands as with a normal Linux terminal. To get an interactive shell of a stopped (not in running state) container, you can use: As you can see, we landed directly inside a new Ubuntu container where we can run our commands. If a container is already running, you can use exec command as below. First, let’s find out the container ID. And, then get inside container ID c2d969adde7a In the above output, you can observe that we started a bash session of nginx container which was in running state. Here we can execute any supported command and get the output. Note – your container may not have bash and if so, you can use sh. Ex:

Direct Output

Often we just need the output of one or two commands and do not require a full-blown interactive session for our task. You can run the required command inside a container and get its output directly without opening a new shell session using exec command without -it flag. Its syntax would be: Here’s an example: We executed ps -ef | grep mysql command inside the running MariaDB container and got the output directly.

Dockerfile Way

This is not the exact way you can run commands inside a docker container though it may be helpful in development situations or for initial deployment debugging etc. We can use RUN command inside a Dockerfile. Here’s our sample Dockerfile: It simply pulls the latest nginx image from the registry and then runs the nginx -V command to display the Nginx version when you build the image. Observe the output of RUN command in the above snippet. The above snippet will be only displayed on the first build and consecutive builds will no-repeat the RUN command output. As a workaround, you can try –no-cache flag: The last method is not the best way but can be sometimes helpful for debugging etc.

Summary

Running command inside a docker container is simple and there are a few methods available to do it. It is a regular task of a Docker Administrator, so knowing these commands is useful. Next, learn some of the popular Docker commands.