How to Enter a Docker Container Already Running with a New TTY

When working with Docker, sometimes you need to jump into a running container to inspect logs, debug issues, or run additional commands. Luckily, Docker makes it easy to open a new interactive terminal (TTY) inside an already running container.


1️⃣ The Problem

You’ve already started a container in the background or in detached mode (-d). Now, you want to connect to it again with an interactive shell.

If you try:

docker attach <container_id_or_name>

You’ll be attached to the main process (PID 1), which isn’t always useful and can even freeze your terminal if it doesn’t accept input.

The better solution is to create a new TTY session.


2️⃣ The Solution: docker exec

The correct way to enter an already running container with a new TTY is to use:

docker exec -it <container_id_or_name> /bin/bash

or, if bash isn’t installed:

docker exec -it <container_id_or_name> /bin/sh

Here’s what the flags mean:

  • exec → runs a command in a running container
  • -i → keeps STDIN open
  • -t → allocates a TTY (pseudo-terminal)
  • /bin/bash → starts a bash shell (or sh)

3️⃣ Example

Start a container in detached mode:

docker run -dit ubuntu

Check running containers:

docker ps

Enter it with a new TTY:

docker exec -it <container_id> bash

Now you’re inside the container with a fresh shell, independent of the original process.


4️⃣ Alternative: docker attach vs docker exec

CommandUse CaseDrawback
docker attachAttach to the main container processCan freeze if process doesn’t accept input
docker exec -itOpen a new shell/TTYSafer, allows multiple interactive sessions

👉 For debugging and exploration, always prefer docker exec.


5️⃣ Bonus: Run Multiple TTYs

You can even open multiple interactive shells to the same container:

docker exec -it <container_id> bash
docker exec -it <container_id> bash

Each command opens a new independent terminal session.


📌 Summary

To enter a running container with a new TTY:

docker exec -it <container_id_or_name> bash
  • ✅ Use bash if available, or sh as a fallback
  • ✅ Prefer docker exec over docker attach for safety
  • ✅ Open multiple TTYs if needed for debugging

This is one of the most common commands you’ll use when managing containers in development and production.

Sharing Is Caring:

Leave a Comment