How to Run an Interactive Shell Using Docker Compose

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 your docker-compose.yml
  • bash → the command to run (you can use sh if bash is 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

CommandBehavior
docker-compose runStarts a new container based on the service configuration
docker-compose execConnects 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 bash is installed. Alpine-based images usually only have sh.
  • For quick one-off commands: docker-compose exec web ls -la
  • To avoid confusion, prefer exec for containers started with docker-compose up.

📌 Summary

To open an interactive shell with Docker Compose:

  • Use docker-compose exec service bash for existing containers.
  • Use docker-compose run service bash for a new container session.
  • Use sh if bash is not available.

This makes debugging and development with Docker Compose much easier and faster.

Sharing Is Caring:

Leave a Comment