How to Use docker exec: Run Commands Inside Containers
Use
docker exec to run commands inside a running Docker container. The basic syntax is docker exec [options] container_name command, which lets you execute commands interactively or in the background inside the container.Syntax
The docker exec command runs a command inside a running container.
docker exec: The command to run a process inside a container.[options]: Optional flags like-itfor interactive mode.container_name: The name or ID of the running container.command: The command you want to run inside the container.
bash
docker exec [options] container_name command
Example
This example shows how to open an interactive shell inside a running container named my_container. It lets you run commands inside the container as if you were logged into it.
bash
docker exec -it my_container /bin/bash
Output
root@container_id:/#
Common Pitfalls
Common mistakes when using docker exec include:
- Trying to run commands on a container that is not running.
- Forgetting the
-itoption when you want an interactive shell, which causes the shell to exit immediately. - Using the wrong container name or ID.
Always check your container status with docker ps before using docker exec.
bash
docker exec my_container /bin/bash # This will fail if the container is not running or if you want an interactive shell without -it docker exec -it my_container /bin/bash # Correct way to open an interactive shell
Quick Reference
Here is a quick cheat sheet for common docker exec options:
| Option | Description |
|---|---|
| -i | Keep STDIN open (interactive input) |
| -t | Allocate a pseudo-TTY (terminal) |
| -d | Run command in the background (detached) |
| --user | Run command as a specific user inside the container |
Key Takeaways
Use
docker exec -it container_name command to run interactive commands inside a running container.Always ensure the container is running before using
docker exec by checking with docker ps.The
-it option is essential for interactive shells like /bin/bash.You can run commands in the background with the
-d option.Use the container name or ID correctly to avoid errors.