Although it may seem like manually executing commands inside Docker containers could be considered as an antipattern, actually it might be useful for instance when debugging things in non-production environments. This is done with the docker exec
command which obviously starts a new command in a running container. Without further ado let’s see how it’s done.
Prerequisites
- Docker
Solution
Step 1. Connect to the running container node (instance) and run the following command:
docker exec -it <container_id_or_name> echo "Hi there from container!"
Usually, docker exec
is used when attaching a shell though, so if you want to connect to the container first, run the following command:
docker exec -it <container_id_or_name> /bin/sh
Note(s): If /bin/bash throws an error, try with /bin/sh.
Conclusion
Do you agree that running commands from inside running containers is a bad practice? Why or why not? Please let me know in the comment section below. On a side note, follow our official channel on Telegram.