When working with Docker, sometimes you need to “get inside” a running container to inspect logs, debug errors, or manually test the application. Thankfully, Docker provides simple ways to access a container’s shell environment.
In this blog, we’ll show you how to enter a Docker container’s shell using a few different commands depending on the container’s setup.
🔍 Why Enter a Docker Container?
Here are a few common reasons:
- Debugging configuration or environment issues
- Running database queries directly
- Checking file structures and logs
- Installing or testing tools interactively
✅ Prerequisites
- Docker must be installed and running
- You should know your container ID or name
- The container should be running
Use the following to list containers:
docker ps
🔧 Method 1: Using docker exec (Recommended)
This is the most common and preferred method.
Example for a container with bash:
docker exec -it container_name_or_id bash
-i: Interactive mode-t: Allocate a pseudo-TTY (for terminal-like behavior)
Example for containers without bash (use sh):
docker exec -it container_name_or_id sh
⚠️ Not all containers have
bash. Alpine-based images usually only havesh.
🧰 Method 2: Using docker attach
This command connects to the main process of the container (usually the app itself), not always a shell.
docker attach container_name_or_id
Drawback:
- You may not get a shell
- Exiting can shut down the container unless detached properly (
Ctrl + P + Q)
🧪 Method 3: Start a Shell When Container Launches
You can override the default command when starting a container:
docker run -it image_name bash
This launches a container and drops you right into the shell.
🛠 Tip: Checking Available Shells
If you’re unsure whether a shell exists in the container, try this:
docker exec -it container_name_or_id cat /etc/shells
Then use the available one (e.g., /bin/bash or /bin/sh).
🧵 Summary
| Command | Purpose |
|---|---|
docker exec -it CONTAINER bash | Start a new shell session inside a running container |
docker exec -it CONTAINER sh | Use if bash is unavailable |
docker attach CONTAINER | Attach to the main process (not recommended for interactive shell use) |
docker run -it IMAGE bash | Run a new container with an interactive shell |
🚀 Final Words
Knowing how to access a container’s shell is crucial for real-time debugging and hands-on management. Whether you’re troubleshooting a broken service or exploring containerized environments, these commands will make you more effective with Docker.