⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Docker & Containers Interview Questions Scenario 21 of 159 in Docker & Containers
Junior / Associate DevOps [L1] Docker Core Fundamentals [L1]
🎯 Target Role / Context: Docker Scenario #21 (L1) · Docker

Q: How do you get a shell inside a running container?

docker exec -it <container> bash or sh if bash isn't available.

#Docker #L1 #Containers #Linux
🎙️ Candidate Opening & Architectural Context
"To <strong>get a shell inside a running container</strong>, run <code>docker exec -it &lt;container&gt; sh</code> (or <code>bash</code> when the image ships it). <code>exec</code> starts a new process in the container's existing namespaces, so leaving the shell does not stop the container. Interviewers ask this to check you know the difference from <code>docker attach</code> and <code>docker run</code>, and what to do when there is no shell at all, as in distroless or scratch images. Strong answers cover debugging safely without changing production state."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's Docker Certified Associate (DCA) Hands-On Lab Course covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: To <strong>get a shell inside a running container</strong>, run <code>docker exec -it &lt;container&gt; sh</code> (or <code>bash</code> when the image ships it). <code>exec</code> starts a new process in the container's existing namespaces, so leaving the shell does not stop the container. Interviewers ask this to check you know the difference from <code>docker attach</code> and <code>docker run</code>, and what to do when there is no shell at all, as in distroless or scratch images. Strong answers cover debugging safely without changing production state.

1️⃣

Mental model: exec starts a second process

A container is just processes isolated by namespaces and cgroups. docker exec joins those namespaces with a new process.

  • exec: spawns an additional process (your shell) inside a running container. Exiting it does not affect the main process.
  • attach: connects your terminal to the container's main process (PID 1) stdin/stdout. Pressing Ctrl+C or exiting can stop the container, so it is rarely what you want for debugging.
  • run: creates a brand-new container. docker run -it image sh is for exploring an image, not the live instance.
  • Flags: -i keeps stdin open, -t allocates a TTY. Use both for interactive shells.
  • Choosing the shell: to learn what is available, try docker exec my-app sh -c 'echo $0; ls /bin' or inspect the image with docker image inspect for its default command and user.
2️⃣

Hands-on: get a shell inside a running container

Pick the shell that exists in the image and the user you need.

docker ps --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}'
docker exec -it my-app sh                 # BusyBox/Alpine
docker exec -it my-app bash               # Debian/Ubuntu based
docker exec -it -u 0 -w /app my-app sh    # root, in /app
docker exec my-app cat /etc/os-release    # one-off, no TTY needed

docker compose exec web sh
  • Alpine and BusyBox images: only sh exists by default, so bash fails with executable file not found.
  • Run as root: --user 0 (or -u root) helps when the app user cannot install or inspect things. Use it sparingly on production.
  • Set context: -w /app sets the working directory and -e KEY=value adds a variable for that session only.
  • Compose: docker compose exec web sh targets a service by name without finding the container name.
  • Environment differences: an exec session does not run the container's entrypoint script, so variables set by that script may be missing. Use docker exec my-app env and compare with the application's own view.
Advertisement
3️⃣

When the image has no shell

Distroless and scratch images deliberately omit shells and package managers, so exec sh fails.

# Debug sidecar sharing the target's PID and network namespaces
docker run --rm -it \
  --pid=container:my-app --net=container:my-app \
  nicolaka/netshoot sh
# ps aux  -> shows the app's processes
# ss -tlnp -> shows its listening sockets
  • Share namespaces from a debug container: start a tooling image attached to the target's PID and network namespaces.
  • Docker Debug: docker debug <container> is available in recent Docker Desktop and CLI releases (check your subscription and version) and injects a toolbox without modifying the image.
  • Kubernetes equivalent: kubectl debug -it pod/my-app --image=busybox:1.36 --target=app adds an ephemeral container.
  • Copy files out instead: sometimes docker cp and reading logs is all you need.
  • Non-interactive use: in scripts drop -t and use -i only when piping input. A TTY in CI logs produces carriage returns and breaks automation.
Pro Tip: The debug container sees the target's processes and network but not its filesystem by default. Reach it through <code>/proc/&lt;pid&gt;/root</code> when your privileges allow.
4️⃣

Verify and handle common errors

Read the error text, because each one points at a different cause.

  • Container is not running: docker exec only works on running containers. Check docker ps -a and docker logs. For a crashed one, start a copy with docker run -it --entrypoint sh image.
  • OCI runtime exec failed: usually means the binary (bash) is not in the image. Try sh.
  • Confirm where you are: inside the shell, hostname equals the container ID and ps shows few processes, proving you are in the container, not the host.
  • Garbled terminal: missing -t causes odd line handling. Resize problems often fix with stty rows 40 cols 120.
  • Exited containers: to look inside a crashed container's files, either docker cp out the paths you need or create an image from it with docker commit and run that image with an overridden entrypoint.
5️⃣

Production practice: debug without drift

Shell access in production is a change surface, so treat it that way.

  • Immutable mindset: do not install tools or edit files in a live container. They vanish on redeploy and hide the true state.
  • Audit access: limit who can reach the Docker socket or kubectl exec, and log exec events through audit tooling.
  • Prefer observability: logs, metrics and traces answer most questions, leaving exec for last-resort inspection.
  • Remote hosts: use a Docker context or SSH to reach the daemon, for example docker --context prod exec -it my-app sh, rather than sharing the daemon port unauthenticated over the network.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Use <code>docker exec</code> rather than <code>attach</code>, and for distroless images join the target's namespaces with a debug container instead of rebuilding the image with a shell."
⚡ 60-Second Elevator Pitch Talking Points
  • I run <code>docker exec -it container sh</code>, which starts a new process in the running container's namespaces and leaves the main process untouched.
  • If bash is missing I use sh, and for distroless images I attach a debug container with <code>--pid</code> and <code>--net</code>, or use <code>kubectl debug</code> in Kubernetes.
  • I treat the session as read-only inspection and move fixes into the image or manifest.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Using docker attach to get a shell It connects to PID 1, so exiting or Ctrl+C can stop the container.
  2. Assuming bash exists in every image Alpine and many slim images only have sh, producing an executable-not-found error.
  3. Installing debug tools in a live container Changes are lost on recreate and make the running state diverge from the image.
  4. Forgetting that exec needs a running container A crash-looping container cannot be exec'd into. Inspect logs or run the image with an overridden entrypoint instead.
Advertisement
Want more Docker & Containers scenarios?
Explore our complete collection of scenario-based Docker & Containers interview runbooks.
Browse All Docker & Containers Questions →