Docker - Run a command in a container using the docker exec command

This assumes you have installed Docker on Linux and Docker is running.

A Docker image contains the code used to create a Docker container, such as creating a Nginx web server, or a mySQL server, or a home grown app, and the list goes on. In this way, an image is like a template used to create a container. An image is kind of like a virtual machine, but much more light weight, using significantly less storage a memory (containers are usually megabytes in size).

You will want to first issue the docker ps or docker container ls command to get the list of containers. Let's say the docker ps command returns the following.

CONTAINER ID     IMAGE              COMMAND                 CREATED         STATUS     PORTS     NAMES
d937372c09ab9    b939aa938add9913   "/docker-entrypoin..."  6 minutes ago   Created              my-container

 

The docker exec command is used to run a command in a container. In this example, the df command will be run in the container.

docker exec d937372c09ab9 df

 

Something like this should be returned.

Filesystem                           1K-blocks     Used Available Use% Mounted on
/dev/sda1                               372607   170989    177862  50% /boot
/dev/sda2                               129774     6994    122780   6% /opt

 

The -it or --interactive flag is used to create an interactive tty and the /bin/sh or /bin/bash command can be used to get an interactive shell in the container.

docker exec -it d937372c09ab9 /bin/sh

 

This would return the following interactive prompt where commands can be issued.

/ #

 

For example, the ip address command could be issued to return the ip address of the container.

/ # ip address

 

When done, use exit to exit the container.

/ # exit

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee

Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 40eff in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |