Containers & Exec

How to Exec / SSH into a Running Docker Container with Bash

Open an interactive terminal shell session inside a live running Docker container to inspect files, debug processes, or test network connectivity.

Quick Docker Solution
Safe CommandBeginner
docker exec -it <container-name> /bin/bash
When to use this scenario:You need to inspect runtime environment variables, database connectivity, or investigate file permissions inside a live container without restarting it.

Step-by-Step Execution Guide

1Find container name or ID
docker ps

Lists all currently running containers with their IDs, names, status, and port mappings.

2Launch interactive Bash session
docker exec -it <container-name> /bin/bash

-i (interactive) and -t (pseudo-TTY) allocate a terminal shell. /bin/bash starts the Bash shell.

3Fallback for Alpine Linux images (No Bash)
docker exec -it <container-name> /bin/sh

Alpine and minimal scratch images do not have Bash installed; use /bin/sh instead.

4Exec as root user (Debugging permissions)
docker exec -u 0 -it <container-name> /bin/bash

-u 0 (or --user root) forces root execution even if the container runs as a non-privileged user.

Critical Docker Pitfalls & Precautions

  • β€’Changes made inside a container via exec are ephemeral; they will be lost when the container is recreated unless persisted in volumes.
  • β€’Type "exit" or press Ctrl+D to leave the container shell without stopping the container.

Alternative Approaches

Docker Compose
docker compose exec <service-name> sh

When running multi-container stacks via docker-compose.yml.

Frequently Asked Questions

Exec into Container (Bash/Sh) - Frequently Asked Questions

Common questions about container isolation, signal handling, and runtime behavior.

The container base image (like Alpine or distroless) does not include Bash. Replace /bin/bash with /bin/sh.