When working with Docker Compose, you usually start services in the background with:
docker-compose up -d
But sometimes you need to open an interactive shell inside a container for debugging, testing, or development. Let’s see how to do this properly.
1️⃣ Using docker-compose run
The most direct way is to use the run command:
docker-compose run --rm service_name bash
service_name→ the service defined in yourdocker-compose.ymlbash→ the command to run (you can useshifbashis not installed)--rm→ removes the container after exit (keeps things clean)
✅ Example:
docker-compose run --rm web bash
This will drop you into a new container for the web service with an interactive shell.
2️⃣ Using docker-compose exec
If your service is already running, use:
docker-compose exec service_name bash
✅ Example:
docker-compose exec db bash
This connects you to a running container rather than starting a new one.
👉 Use sh if bash isn’t available:
docker-compose exec db sh
3️⃣ Difference Between run and exec
| Command | Behavior |
|---|---|
docker-compose run | Starts a new container based on the service configuration |
docker-compose exec | Connects to an already running container |
If you want to debug a service that’s already up → use exec.
If you want a fresh temporary container → use run.
4️⃣ Running as Root User
If you need root access inside the container:
docker-compose exec --user root service_name bash
5️⃣ Quick Tips
- Always check whether
bashis installed. Alpine-based images usually only havesh. - For quick one-off commands:
docker-compose exec web ls -la - To avoid confusion, prefer
execfor containers started withdocker-compose up.
📌 Summary
To open an interactive shell with Docker Compose:
- Use
docker-compose exec service bashfor existing containers. - Use
docker-compose run service bashfor a new container session. - Use
shifbashis not available.
This makes debugging and development with Docker Compose much easier and faster.