Shell into a container to debug
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's API container keeps stopping and the logs say nothing useful. You need to look inside: open a shell, query the database, read the container's state and rescue the evidence.
docker exec -it: a shell inside a running container
docker exec starts an extra process inside a container that is already running. With -it (interactive, with a terminal) and a shell such as bash or sh, you get a prompt inside the container.
ShopLite's database is running. Open a shell inside it to look around, run one-off commands, and see what happens when an image has no shell.
Example 1 · Open a shell in shoplite-db, and what happens without one
Runs in: a terminal with Docker installed
docker exec -it shoplite-db bash # an interactive shell inside the container# now you are inside (the prompt changes)whoamils /var/lib/mysql | head -5env | grep MYSQL_DATABASEexit# a one-off command, no shell neededdocker exec shoplite-db ls /docker-entrypoint-initdb.d# a distroless image (no shell at all), e.g. a Java app on gcr.io/distroless/java21-debian12docker exec -it distroless-demo shbash-5.1# whoami root bash-5.1# ls /var/lib/mysql | head -5 #ib_16384_0.dblwr #ib_16384_1.dblwr #innodb_redo #innodb_temp auto.cnf bash-5.1# env | grep MYSQL_DATABASE MYSQL_DATABASE=shoplite bash-5.1# exit exit (no output: the folder is empty) OCI runtime exec failed: exec failed: unable to start container process: exec: "sh": executable file not found in $PATH: unknown
What this code does
- Inside the shell you are
rootin the container's own file system:/var/lib/mysqlshows MySQL's data files (stored in theshoplite-datavolume) andenvshows the variables the container received. docker exec shoplite-db ls ...without-itruns one command and returns; an empty folder simply prints nothing.- The distroless image has no
sh, so Docker cannot start one: the error is about a missing program, not about the container being broken.
Without -it, docker exec runs one command and prints its output, which is handy in scripts. Type exit (or Ctrl+D) to leave a shell; the container keeps running, because you only stopped the extra process.
Not every image has a shell. Debian and Ubuntu based images such as mysql and eclipse-temurin have bash; Alpine images have only sh; distroless images (only the app and its runtime, no shell, no package manager) have neither, and exec fails with "executable file not found". For those, use docker logs, docker inspect, docker cp, or run the same app on a debug image.
Running mysql inside the MySQL container
The mysql image ships with the mysql command line client. Use it inside shoplite-db to check ShopLite's tables and Flyway history.
Example 2 · Check tables and Flyway history with mysql inside the container
Runs in: a terminal with Docker installed
docker exec -it shoplite-db mysql -u shoplite -p shoplitemysql> SHOW TABLES;mysql> SELECT version, description, success FROM flyway_schema_history;mysql> exit# one command, password from a prompt, output straight to your terminaldocker exec -it shoplite-db mysql -u shoplite -p -e "SELECT COUNT(*) AS products FROM shoplite.products;"Enter password: mysql> SHOW TABLES; +-----------------------+ | Tables_in_shoplite | +-----------------------+ | addresses | | app_user | | categories | | customers | | flyway_schema_history | | order_items | | orders | | products | | refresh_token | | user_role | +-----------------------+ 10 rows in set (0.01 sec) mysql> SELECT version, description, success FROM flyway_schema_history; +---------+--------------------------+---------+ | version | description | success | +---------+--------------------------+---------+ | 1 | create schema | 1 | | 1.1 | sample data | 1 | | 2 | add order history index | 1 | | 3 | add product search index | 1 | | 4 | create users and roles | 1 | | 4.1 | seed dev users | 1 | | 5 | create refresh token | 1 | | 5.1 | seed second customer | 1 | +---------+--------------------------+---------+ 8 rows in set (0.00 sec) Enter password: +----------+ | products | +----------+ | 15 | +----------+
What this code does
docker exec -it shoplite-db mysql ...starts the client inside the container, so it connects to the local server: no-h, no-P 3307.flyway_schema_historylists every applied migration withsuccess = 1. It is the first place to look when the app says the schema is wrong.- With
-ethe client runs one statement and exits;-itis still needed so you can type the password at the prompt.
docker exec -it shoplite-db mysql -u shoplite -p shoplite gives you a MySQL prompt without installing anything on your laptop. Inside the container MySQL is local, so no host, port or port mapping is needed.
This is the quickest way to answer "did Flyway run?", "is the row there?" or "which user am I?". -e "SQL" runs one statement and exits, which suits scripts and quick checks.
-pPassword: a password on the command line ends up in your shell history.docker inspect and docker stats
docker inspect prints a container's full configuration and state as JSON: its IP address, mounts, environment variables, exit code and more. --format with a Go template picks one field, such as {{.State.ExitCode}}.
Ask Docker for a container's state, IP address, mounts and environment, then take a snapshot of its CPU and memory.
Example 3 · docker inspect fields and a docker stats snapshot
Runs in: a terminal with Docker installed
docker inspect shoplite-db --format '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}'docker inspect shoplite-db --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'docker inspect shoplite-db --format '{{range .Mounts}}{{.Type}} {{.Name}} -> {{.Destination}}{{end}}'docker inspect shoplite-db --format '{{json .Config.Env}}'docker stats --no-streamrunning exit=0 oom=false 172.17.0.2 volume shoplite-data -> /var/lib/mysql ["MYSQL_ROOT_PASSWORD=root-dev-pass","MYSQL_DATABASE=shoplite","MYSQL_USER=shoplite","MYSQL_PASSWORD=shoplite-dev-pass","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin","GOSU_VERSION=1.17","MYSQL_MAJOR=8.4","MYSQL_VERSION=8.4.6-1.el9","MYSQL_SHELL_VERSION=8.4.6-1.el9"] CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS 7c1e4b9a2f3d shoplite-db 0.62% 412.5MiB / 7.653GiB 5.26% 18.4kB / 25.1kB 41.2MB / 368MB 36
What this code does
- Each
--formatpicks one part of the JSON: state and exit code, the IP on the default network, the mounts, and the environment as a JSON list. - The environment shows both MySQL passwords in plain text: anyone who can run
docker inspectcan read values passed with-eor--env-file. docker stats --no-streamshows MySQL using about 412 MiB; with no-mlimit, LIMIT is all the memory Docker Desktop's virtual machine has.
docker stats shows live CPU, memory, network and disk use for each running container; --no-stream prints one snapshot and exits. A memory number close to the LIMIT column is the warning sign for the out-of-memory kill described in the next section.
Fields worth knowing:
.State.Status,.State.ExitCode,.State.OOMKilled: how the container is or how it stopped..NetworkSettings.Networks: the container's IP on each Docker network (used between containers, not from your laptop)..Mounts: which volume or folder is mounted where; confirmsshoplite-datais on/var/lib/mysql..Config.Env: every environment variable, passwords included in plain text, which is why secrets passed with-eare not hidden.
Reading exit codes: 0, 1, 137, 143
An exit code is the number a process returns when it ends; docker ps -a shows it as Exited (code). 0 means a normal finish, small numbers are errors chosen by the program, and codes above 128 mean a signal stopped it.
Every stopped container leaves a number behind. This Java method turns exit codes into plain explanations.
Example 4 · Explain an exit code in Java
public class ExitCodeDemo {
static String explain(int code) { if (code == 0) { return "finished normally"; } if (code == 1) { return "the app failed: an uncaught exception or System.exit(1)"; } if (code > 128 && code < 160) { int signal = code - 128; String meaning = switch (signal) { case 2 -> "SIGINT, like pressing Ctrl+C"; case 9 -> "SIGKILL: docker kill, a stop that ran out of time, or the out-of-memory killer"; case 15 -> "SIGTERM: a polite stop request, usually docker stop"; default -> "another signal"; }; return "stopped by signal " + signal + " (" + code + " - 128) = " + meaning; } return "an error code chosen by the app itself"; }
public static void main(String[] args) { int[] codes = {0, 1, 137, 143, 130, 3}; for (int code : codes) { System.out.println("Exited (" + code + ") -> " + explain(code)); } }}Exited (0) -> finished normally Exited (1) -> the app failed: an uncaught exception or System.exit(1) Exited (137) -> stopped by signal 9 (137 - 128) = SIGKILL: docker kill, a stop that ran out of time, or the out-of-memory killer Exited (143) -> stopped by signal 15 (143 - 128) = SIGTERM: a polite stop request, usually docker stop Exited (130) -> stopped by signal 2 (130 - 128) = SIGINT, like pressing Ctrl+C Exited (3) -> an error code chosen by the app itself
What this code does
- Codes above 128 are turned back into a signal number with
code - 128; aswitchnames the three signals you meet most often. - 0 and 1 are handled first, and any other small number is the program's own choice: for example, the JVM option
-XX:+ExitOnOutOfMemoryErrorexits with 3. - 130 (128 + 2, SIGINT) is what you see when you press Ctrl+C on a container started with
docker run -it.
A Java app that dies from an uncaught exception exits with 1. Above 128, the code minus 128 is the signal number. 143 = 128 + 15 (SIGTERM): someone asked the process to stop, usually docker stop. 137 = 128 + 9 (SIGKILL): the process was killed at once, by docker kill, by docker stop after its 10-second grace period ran out, or by the kernel's out-of-memory killer.
To tell the 137 cases apart, check docker inspect --format '{{.State.OOMKilled}}'. true means the container used more memory than its -m limit. That is different from a Java OutOfMemoryError, where the heap is full but the JVM itself is still alive to report it.
Predict the output
Why did it stop?
Read the facts from docker ps and docker inspect. Pick the cause.
Round 1 of 2
shoplite-api has a 512 MB memory limit.
docker stop depends on the app: MySQL handles SIGTERM and exits with 0, while a plain Java app shows 143.docker cp, and why changes made with exec are lost
docker cp copies files between a container and your computer, in either direction. It also works on a stopped container, which makes it the way to rescue a heap dump or log file from an app that just died.
The API container died with an out-of-memory error. Find out why, and copy the heap dump out of the stopped container.
Example 5 · Rescue a heap dump with docker cp
Runs in: a terminal with Docker installed
# shoplite-api runs with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp# -XX:+ExitOnOutOfMemoryError, and it has stopped. Find out why:docker ps -a --filter name=shoplite-api --format "{{.Names}} {{.Status}}"docker inspect shoplite-api --format "exit={{.State.ExitCode}} oom={{.State.OOMKilled}}"docker logs --tail 4 shoplite-api# copy files OUT of the container (works on stopped containers too)docker cp shoplite-api:/tmp/java_pid1.hprof ./heap.hprof# copy a file IN (a quick test only: lost when the container is recreated)docker cp ./fix.sql shoplite-db:/tmp/fix.sqlshoplite-api Exited (3) 2 minutes ago exit=3 oom=false java.lang.OutOfMemoryError: Java heap space Dumping heap to /tmp/java_pid1.hprof ... Heap dump file created [301245112 bytes in 1.204 secs] Terminating due to java.lang.OutOfMemoryError: Java heap space Successfully copied 301MB to /home/asha/shoplite-api/heap.hprof Successfully copied 2.05kB to shoplite-db:/tmp/fix.sql
What this code does
- Exit code 3 with
OOMKilled=falsemeans the JVM itself gave up on a full heap (-XX:+ExitOnOutOfMemoryError), after writing a heap dump. An exit code of 137 withOOMKilled=truewould mean the kernel killed the whole container, with no chance to write anything. docker cpcopies the dump out of the stopped container; open it with a heap analyser such as Eclipse MAT. Do this beforedocker rm, which deletes the file with the container.- Copying
fix.sqlintoshoplite-dbis fine for a quick test, but it disappears when the container is recreated; the real change belongs in a Flyway migration.
Everything you change inside a container with exec or cp (an edited config file, an installed tool, a copied script) lives only in that container's own writable layer. docker rm deletes it, and the next docker run starts again from the image.
So use exec to look and to test, then make the real fix in the image, the configuration or a migration, and copy the evidence out before you remove anything.
Order of execution
Rescue, then clean up
Put the steps for a crashed shoplite-api in a sensible order.
Next step
Check your understanding
12 quick questions