When working with Docker, you might have an existing container running (or stopped) and want to execute a command inside it without creating a new container. Docker provides a straightforward way to do this using the docker exec and docker run commands.
🔹 When You Might Need This
You may need to:
- Debug an application by running diagnostic commands.
- Install additional tools inside a running container.
- Open a shell session for manual inspection.
- Check logs, configurations, or environment variables.
1️⃣ Using docker exec for Running Commands in a Running Container
The docker exec command allows you to run commands inside a currently running container.
Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Example – List files in / inside the container:
docker exec my_container ls /
Example – Start an interactive bash shell:
docker exec -it my_container bash
Use
-itfor interactive mode (-i= keep STDIN open,-t= allocate a pseudo-TTY).
If your container doesn’t have bash, you can try:
docker exec -it my_container sh
2️⃣ Using docker run for New Containers From the Same Image
If the original container is stopped and you just want to run a command using its image (not the exact container state):
docker run -it my_image bash
This creates a new container from the same image, which is different from exec (which works inside an existing one).
3️⃣ Running a Command in a Stopped Container
docker exec works only on running containers. If your container is stopped:
- Start it again:
docker start my_container - Then run your command:
docker exec -it my_container bash
If you want to inspect files from a stopped container without starting it, you can:
docker cp my_container:/path/in/container /path/on/host
Or commit the container to an image:
docker commit my_container my_new_image
docker run -it my_new_image bash
4️⃣ Practical Examples
Check environment variables:
docker exec my_container printenv
View application logs inside the container:
docker exec my_container cat /var/log/app.log
Install curl inside the container:
docker exec my_container apt-get update && apt-get install -y curl
📌 Summary
- Use
docker execto run a command inside a running container. - Use
docker startto restart a stopped container before running commands. - For a fresh container from the same image, use
docker run.
Example workflow:
docker ps # Find container name or ID
docker exec -it my_container bash