---
title: "Debugging Docker Containers That Exit Immediately: Causes and Solutions"
date: "2026-11-17T11:45:00+07:00"
description: "Step-by-step troubleshooting guide for Docker containers exiting immediately, covering foreground vs background execution traps, inspecting exit codes, log analysis, and entrypoint overrides."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/debugging-containers-exiting-immediately.jpg"
alt: "Terminal session showing docker container inspection, exit code analysis, and logs"
tags: ['docker', 'containers', 'debugging', 'troubleshooting', 'cli']
---

One of the most common issues developers encounter when working with Docker is running `docker run` or `docker compose up`, only to discover that the container exits immediately with status `Exited (0)` or `Exited (1)`.

Containers do not behave like persistent virtual machines. A Docker container remains running **only as long as its main entrypoint process (PID 1) continues to execute in the foreground**.

This guide outlines why containers exit unexpectedly, how to interpret exit codes, how to inspect container logs, and how to interactive-debug failing containers.

---

## 1. The Fundamental Cause: The PID 1 Lifespan Rule

In Linux container architecture, the container lifecycle is bound to process ID 1 (PID 1).

```text
┌─────────────────────────────────────────────────────────────┐
│                 Container Execution Model                   │
│                                                             │
│  1. Container Starts ──► Spawns ENTRYPOINT / CMD (PID 1)    │
│  2. PID 1 executes tasks                                    │
│  3. PID 1 terminates (Exit Code 0 or non-zero)              │
│  4. Container Stops Immediately ──► Status: Exited          │
└─────────────────────────────────────────────────────────────┘
```

When PID 1 finishes its execution, exits, or crashes, the container stops immediately—regardless of whether other child threads were spawned or background daemons were initiated.

---

## 2. Common Foreground vs. Background Execution Traps

### Scenario A: Running Daemons in Daemonized Background Mode

In traditional Linux server administration, services such as NGINX, Apache, or MySQL are started as background daemons (`systemctl start nginx` or `nginx -g "daemon on;"`).

If you start NGINX inside a container using daemon mode:

```bash
# Bad Dockerfile pattern
CMD ["nginx"]
```

NGINX spawns background worker processes and immediately terminates its initial parent process. Because the parent process exits, Docker assumes the container task is finished and terminates the container.

**Solution**: Run services in the **foreground**:

```dockerfile
# Good Dockerfile pattern: Keep process in foreground
CMD ["nginx", "-g", "daemon off;"]
```

### Scenario B: Utility Images without Interactive Allocation

Running base distribution images (like `ubuntu`, `debian`, or `alpine`) without arguments:

```bash
$ docker run -d ubuntu
a1b2c3d4e5f6

$ docker ps -a
CONTAINER ID   IMAGE    COMMAND       STATUS                   NAMES
a1b2c3d4e5f6   ubuntu   "/bin/bash"   Exited (0) 2 seconds ago  distracted_hopper
```

The default command for `ubuntu` is `/bin/bash`. When run in detached mode (`-d`) without an interactive pseudo-TTY attached, `bash` detects no active `STDIN` stream, reaches end-of-file (EOF), and exits cleanly with exit code `0`.

**Solution**: Pass `-it` (interactive TTY flags) or execute a long-running foreground command:

```bash
# Option 1: Keep shell interactive
docker run -it -d ubuntu

# Option 2: Run a persistent tail/loop command
docker run -d ubuntu tail -f /dev/null
```

---

## 3. Deciphering Container Exit Codes

When a container exits, Docker records an integer Exit Code in its state metadata. Checking the exit code provides immediate clues about why the container stopped.

Inspect exited containers using `docker ps -a` or `docker inspect`:

```bash
docker ps -a --format "table {{.ID}}\t{{.Names}}\t{{.Status}}"
```

Or query exit codes directly:

```bash
docker inspect <container_id> --format='{{.State.ExitCode}}'
```

### Common Container Exit Code Reference

| Exit Code | Meaning | Common Cause & Troubleshooting |
| :--- | :--- | :--- |
| **0** | Clean Exit / Success | Process completed its script or exited normally (e.g. cron job finished or missing foreground flag). |
| **1** | Application Error | Unhandled exception, missing dependency, syntax error in app code, or invalid configuration. |
| **125** | Docker Engine Error | The Docker daemon failed to run the container (e.g. invalid flag or host resource error). |
| **126** | Command Cannot Execute | Script lacks execute permissions (`chmod +x entrypoint.sh`) or missing entrypoint interpreter (`#!/bin/bash`). |
| **127** | Command Not Found | ENTRYPOINT binary or shell path does not exist in container filesystem. |
| **137** | `SIGKILL` / Out Of Memory | Container was killed by Linux OOM Killer (Memory limit exceeded) or stopped via `docker kill`. |
| **139** | `SIGSEGV` | Segmentation fault (invalid memory access in compiled C/Go binaries). |
| **143** | `SIGTERM` | Graceful termination signal sent by `docker stop` or orchestrator. |

---

## 4. Step-by-Step Debugging Workflow

Follow this systematic workflow when troubleshooting a container that exits immediately.

### Step 1: Check Container Logs

The standard log output records `STDOUT` and `STDERR` emitted before crash:

```bash
# Print last 50 lines of logs with timestamps
docker logs --tail 50 --timestamps <container_name_or_id>
```

If the logs show a stack trace or missing configuration error (e.g., `FATAL: database connection failed`), update your environment variables or application configuration accordingly.

### Step 2: Override the ENTRYPOINT with an Interactive Shell

If a container exits before logs can be captured, override the image entrypoint using `--entrypoint` to spawn an interactive shell:

```bash
docker run --rm -it \
  --entrypoint /bin/sh \
  <failing_image_name>
```

For images based on Ubuntu/Debian where `/bin/bash` is present:

```bash
docker run --rm -it \
  --entrypoint /bin/bash \
  <failing_image_name>
```

Once inside the interactive container shell:
1. Check installed files and directory permissions (`ls -la /app`).
2. Verify environment variables (`env`).
3. Execute the original application startup script manually to observe immediate error output.

### Step 3: Inspect Container Mounts and Environment Configuration

Use `docker inspect` to verify environment variables, volume mount paths, and working directories:

```bash
# Check working directory and environment variables
docker inspect --format='{{json .Config.Env}}' <container_id> | jq

# Check volume mount source and target paths
docker inspect --format='{{json .Mounts}}' <container_id> | jq
```

---

## 5. Fixing Script Line Endings (`CRLF` vs `LF`)

A subtle bug causing exit code `127` or `126` occurs when building container images on Windows host systems:

```text
/usr/local/bin/entrypoint.sh: line 2: $'\r': command not found
```

If your `entrypoint.sh` script was saved with Windows `CRLF` line endings instead of Unix `LF` line endings, the Linux kernel fails to parse the `#!/bin/sh\r` shebang line.

**Solution**: Convert line endings to Unix `LF` before building the image, or convert inside your Dockerfile:

```dockerfile
FROM alpine:3.20

COPY entrypoint.sh /usr/local/bin/
RUN dos2unix /usr/local/bin/entrypoint.sh && chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
```

---

## **Takeaway:**

Containers exit immediately when their main PID 1 process finishes or crashes. To debug instantly: inspect the container status code with `docker inspect`, read detailed crash traces using `docker logs`, and override the entrypoint with `docker run -it --entrypoint /bin/sh` to launch an interactive session inside the image filesystem.

---

## Sources

- [Docker Docs: docker logs](https://docs.docker.com/reference/cli/docker/container/logs/)
- [Docker Docs: docker inspect](https://docs.docker.com/reference/cli/docker/container/inspect/)
- [Docker Docs: Dockerfile reference (ENTRYPOINT)](https://docs.docker.com/build/building/packaging/#entrypoint)
