Docker Container Exits Immediately With A Terminal Error And A Container Illustration

Docker Container Exits Immediately? Diagnose And Fix It Safely

Docker container exits immediately? Check logs, exit codes, CMD, ENTRYPOINT, Compose configuration, permissions and memory without losing data.

This guide explains how to distinguish a successful short-lived container from a crashing service, and how to investigate startup failures with Docker’s documented commands without losing persistent data.

Why A Docker Container Can Exit Immediately

A container normally runs for as long as its main process keeps running. That process is selected through the image’s ENTRYPOINT and CMD settings, possibly modified by a command supplied at runtime or by a Compose service. When the main process ends, Docker records the container as exited, even if the software inside it did exactly what the author intended. A short-lived job can therefore finish successfully without being a failed service.

Before changing Docker configuration, decide whether the image should run a long-lived web server, a queue worker, an interactive shell, a scheduled job, or a one-time command. These workloads have different expectations. A successful command-line task should end with an exit status, while a web server usually remains active and listens for requests. The useful question is why the main process ended, not how to force every container to stay alive.

Check Whether The Container Is Actually Exited

Open a terminal where the Docker command-line interface can communicate with the correct Docker Engine. Run docker ps -a to list both running and stopped containers, including their names, images, creation times, statuses and sometimes an exit code. This often clarifies whether the container exited, is restarting repeatedly, or never started as expected. Docker documents the listing and filtering options in its Container List Reference.

Identify the specific name or container ID before issuing another command. When several projects share an Engine, a similar name can refer to the wrong application. If a container was started using the –rm option, Docker may remove it after exit, which means it will not appear in the usual stopped-container list. For troubleshooting, reproduce an authorized test without automatic removal so the final state and logs remain available.

Read The Exit Code Before Guessing

Use docker inspect --format '{{.State.ExitCode}}' CONTAINER_NAME, substituting your actual container name. Docker records the exit status reported when the container’s main process terminates. Zero typically indicates successful completion; a nonzero value generally indicates an error or interruption, but the meaning depends on the program and how the container was stopped. The Docker Running Containers Guide explains the relationship between process exit status and container exit behavior.

Treat exit codes as clues rather than definitive diagnoses. For example, status 137 often corresponds to a process terminated with SIGKILL, which can follow memory pressure but can also result from other forced termination. Status 143 commonly corresponds to SIGTERM and may be normal during graceful shutdown. Inspect additional state and events before asserting that a specific exit code proves an out-of-memory incident or application defect.

View Logs From A Stopped Container

Run docker logs --tail 100 CONTAINER_NAME to view recent standard output and standard error from an existing container. To preserve timestamps when useful, add the documented –timestamps option. For a reproducible startup problem, use Docker Desktop’s Logs view or the CLI to look for missing configuration, invalid arguments, permission errors, failed database connections or a stack trace. Docker’s Container Logs Reference describes how this command works.

An empty log does not prove there was no error. Some applications write messages only to files, use external logging systems or crash before initializing their logger. Check the configured logging driver, container state and host events where appropriate. Do not paste logs containing passwords, tokens, personal data or private URLs into public support requests. Redact them before sharing diagnostic excerpts.

Inspect The Final Container State Safely

The inspection API provides details not shown in a short list. Try docker inspect --format '{{json .State}}' CONTAINER_NAME for the overall state, including the exit code and termination information. A targeted request such as docker inspect --format '{{.State.OOMKilled}}' CONTAINER_NAME can help assess whether the runtime recorded an out-of-memory kill. These are read-only inspections and should generally precede any intervention.

Pay attention to when the container started and finished. A program that runs for one second and exits zero may have completed its designated task, while one that repeatedly exits with the same error during initialization requires a different remedy. Save a sanitized diagnostic snapshot if the issue is intermittent, especially before changing environment variables, replacing images or re-creating containers.

Diagram 1: Diagnose The Exit Before Restarting
docker ps -a
docker inspect
docker logs
Review CMD And ENTRYPOINT
Fix The Actual Cause
Original XYZ Tech instructional diagram. Replace sample names with an authorized container identifier.

Understand CMD, ENTRYPOINT And The Main Process

A Dockerfile can set ENTRYPOINT, CMD or both to determine what the container runs. Docker’s Dockerfile Reference explains how they interact and distinguishes shell and exec forms. If the specified command finishes quickly, the container also ends. A container does not continue running merely because its filesystem contains a server program or because a background command was launched somewhere during startup.

For a long-running service, arrange for the real application process to remain in the foreground as the main process. Do not treat a command such as an endless sleep loop as a production fix, because it merely hides the fact that the intended service is not running. If your image is intentionally designed for batch work, immediate successful exit may be the correct result and needs no repair.

Fix A Startup Script That Exits Too Soon

A common failure involves a shell script that launches an application in the background with an ampersand and then finishes. If the script is the container’s main process, Docker may stop the container even though the author expected the background application to keep it alive. Review the script and use appropriate foreground execution or the shell’s exec command to replace the wrapper with the intended long-lived process.

Test the script’s error handling, working directory and environment assumptions. For example, a missing executable can cause an early nonzero exit while a misplaced exit statement can produce a clean zero exit. Docker’s Exec-Form Guidance explains why exec form is useful for signal handling. Do not simply suppress errors with unconditional success exits because that makes operational monitoring less trustworthy.

Check Whether The Container Was Meant To Be Interactive

An image launched with a shell command may exit after reading end-of-file from standard input when no interactive terminal is attached. That can be normal behavior for a shell that has no commands left to execute. If you are conducting an authorized hands-on diagnostic session, run an appropriate image with interactive and terminal options, or use Docker Desktop’s supported debugging features.

An interactive shell is a debugging tool, not proof that the production service works. The real application’s startup command and runtime dependencies still need to succeed in normal noninteractive operation. If a container stays alive only when an engineer keeps a terminal open, identify why the service process exits rather than adopting manual terminal attachment as the deployment design.

Read Docker Compose Logs And Service Status

For a Compose project, use docker compose ps -a to see service containers and their states. Then run docker compose logs --tail 100 SERVICE_NAME with the correct service name. The official Compose Logs documentation describes the output and options. The project directory and Compose file matter; otherwise you might inspect a different set of containers from the one that failed.

Use docker compose config to see the effective resolved service definition, including command, entrypoint, volumes and environment substitution. This can expose values that differ from what you expected in a short YAML fragment. Because the rendered configuration may include secrets or private paths, treat it as sensitive diagnostic material. Do not paste a full unredacted configuration into an issue tracker.

Check An Overridden Compose Command

A Compose service can override an image’s default command or entrypoint. That is useful when deliberately running migrations or workers, but it can also change the main process from a persistent server to a short-lived command. Compare the Compose service’s command and entrypoint with the Dockerfile and the image’s intended documented usage.

If your Compose service launches a task that exits successfully, verify whether it was supposed to be a one-time job. Do not change it into a never-ending service merely so a dashboard shows green. On the other hand, if the service was supposed to host an application, make sure the correct executable and foreground invocation are present. Keep commands and environment settings in version control without storing credentials in a public repository.

Look For Missing Or Incorrect Environment Variables

Applications often depend on environment settings for listening ports, database connections, feature flags, credentials and file locations. A container may start and immediately fail if a required variable is absent or malformed. Read the application’s error message and the corresponding deployment configuration before inventing values. A database service address, for example, may be different inside a container network than on the host.

Inspect which variables were configured without exposing their secret values to others. Use a managed secret mechanism where appropriate and avoid writing passwords into public commands, example screenshots or build arguments. A missing configuration item is best corrected in the deployment definition or approved secret store, not by making a one-off manual change in a running container that disappears on the next recreation.

Verify The Working Directory And Executable Path

A startup command may use a relative path that works on a developer laptop but does not exist in the built image. Review WORKDIR, COPY instructions, file permissions and the command path in the Dockerfile. Docker’s Dockerfile Overview explains the way those instructions affect the image. If startup logs say an executable or configuration file is missing, compare the built artifact with the intended build context.

Do not assume a successful image build means the runtime command is valid. A build can package the wrong directory, omit a file excluded by .dockerignore or use a base image that lacks a shell or utility expected by a script. Rebuild only after identifying the missing component. Our Docker Image Vs Container Guide clarifies why inspecting the source image is different from inspecting a running instance.

Understand A Container That Exits With Code Zero

Exit code zero is often the most misunderstood result. It usually means the main command completed successfully. A tool that generates a report, prints a version number or applies a database migration can legitimately finish in seconds. The status Exited (0) is then a record of completion rather than proof that Docker or the host failed.

If you expected a persistent server, inspect the command that actually ran. A Docker image that defaults to a shell or a setup task will not necessarily start your server unless its startup command is supplied. Test whether the web service really listens on its intended port before changing restart behavior. Avoid replacing your service’s actual command with a sleep command, because that makes the container stay up without providing the intended functionality.

Investigate Exit Code 137 And Memory Pressure

Exit code 137 commonly indicates SIGKILL, and out-of-memory termination is an important possible cause. Query the recorded OOMKilled state and inspect host or orchestrator events when available. Docker’s Resource Constraints Guide explains memory limits and the Linux out-of-memory killer. A container can also be forcibly stopped for reasons unrelated to memory, so avoid assigning a single cause from the code alone.

If memory pressure is confirmed, review legitimate workload requirements, leaks, concurrency, resource allocation and available host capacity. Increasing the limit may relieve one symptom but is not a substitute for fixing an application that grows without bound. Do not disable out-of-memory protection on a production host as a generic workaround. Use docker stats for live containers and retain monitoring history when failures are intermittent.

Distinguish Exit Code 143 From A Crash

Exit code 143 typically corresponds to a process terminated by SIGTERM. A user request to stop a container, a deployment update or a controlled shutdown can therefore produce this result. Look at who or what initiated termination before investigating a software crash. Docker’s container lifecycle reference explains signal and exit behavior and the role of the process running in the container.

Where an application handles termination properly, it may finish outstanding work and then exit. A server that cannot respond to termination can be forcibly killed after a grace period. Diagnose whether the shutdown was expected, whether it occurred during deployment and whether data was safely written. Avoid treating every nonzero status as a code defect when it may be normal orchestration behavior.

Check File Permissions, Bind Mounts And Ownership

Some applications stop immediately because the configured user cannot read a configuration file or write to a required directory. If a host directory is bind-mounted, its ownership and permissions differ from files baked into an image. Examine the exact error and mounted path before applying permission changes. The relationship between Docker-managed volumes and bind mounts is explained in our Docker Volume Vs Bind Mount Guide.

Do not fix a permission error by making the application run as root without understanding the security consequences. Prefer a writable directory owned by the intended service user and mount it with appropriate access. Never recursively change permissions on a broad host directory merely to make a container start. Validate ownership and storage behavior on a small controlled test before modifying production data.

Observed ResultPossible MeaningFirst Verification
Exited (0)Main Process Finished NormallyConfirm Intended Workload
Exited (1)Application Reported FailureRead Logs And Command
Exited (137)Forced Kill, Sometimes OOMInspect OOMKilled And Events
Exited (143)SIGTERM, Possibly Normal StopCheck Deployment Or Stop Events
RestartingFailure Combined With Restart PolicyInspect Logs And Compose Config
Running But UnhealthyProcess Alive, Health Check FailingReview Check And Application Endpoint

Separate A Health Check Failure From An Exited Container

A health check marks whether an application appears healthy according to a configured test, but it does not keep the main process alive. A container can be running and unhealthy, or it can exit before a health check has a useful result. The Dockerfile reference describes HEALTHCHECK configuration and how tests are evaluated. A failing health check should prompt investigation of the application endpoint, readiness timing and test command.

Do not assume that an unhealthy status is interchangeable with Exited or Restarting. Investigate the main process and exit code first, then examine health check output for a running service. A healthy-looking process can still have application-level bugs, while a brand-new service might need a legitimate startup interval. Use realistic readiness and liveness checks instead of a hard-coded delay that hides failures.

Avoid Using Restart Policies As The First Fix

Docker supports restart policies such as no, on-failure, always and unless-stopped. These can be appropriate for reliable long-running services after the underlying startup command works. Docker’s Restart Policy Guide explains the options and important behavior. An automatic restart can also create an endless loop that repeatedly floods logs, consumes resources or hits an external service.

Do not use always merely to mask an application that crashes on every start. Check error output and correct the fault first. A one-time migration, report generator or maintenance job often should not restart forever. Make the restart choice part of a documented workload design, not a reflexive response to the word Exited. Confirm the impact on monitoring and dependent services before enabling automatic retries.

What To Check When The Container Keeps Restarting

If the status alternates between Restarting and brief Running states, inspect the recent logs, effective command and restart policy. A crash loop can prevent you from using docker exec because the target container must be running at that moment. In this case, use read-only inspection, logs, Compose configuration and a safe reproduction rather than repeatedly chasing the brief startup window.

Preserve the last known configuration and avoid deleting volumes. If the deployment uses a managed orchestrator, investigate its restart events and workload configuration as well as the image command. A database that is not ready, a missing secret or a failing startup migration can trigger repeated attempts. Fix the dependency rather than hiding the failure with excessively long retry intervals.

Check Dependencies Without Assuming They Are Ready

A service may start before its database, message broker, API or network share is available. The application might terminate at the first connection failure instead of retrying. Check the actual dependency address, authentication, expected port and readiness behavior through appropriate authorized tools. A dependency merely being created or running does not mean it is ready to accept useful work.

Build reliable startup behavior into the application where practical, using bounded retries and meaningful error messages. Compose can express dependency relationships, but you still need to consider readiness and application recovery. Do not hardcode sensitive database credentials into an image. Our Software Repository Guide explains why configuration and source files should be maintained consistently while secret values are managed separately.

Investigate Missing Files After Rebuilding An Image

A newly rebuilt image may not contain files copied by an earlier development workflow. Inspect the build context, ignored paths, working directory and source stage in a multi-stage Dockerfile. A copied configuration file may be present in one build stage but absent from the final runtime image. Logs reporting missing modules or templates should be followed back to build instructions and not treated as unexplained Docker instability.

A container is a running instance of an image plus runtime configuration. If a file previously existed only inside a removed container, rebuilding will not preserve that change automatically. Keep persistent data in the appropriate managed volume or backing service, and keep application code in the image build. These distinctions help you avoid deleting irreplaceable data while attempting a simple startup fix.

Inspect Exit Behavior In Docker Desktop

Docker Desktop provides a graphical Containers view with status, logs and inspect information. Select the intended container or Compose project, confirm the container ID and open the Logs or Inspect panels. Docker’s Containers View Documentation describes the supported interface. The presentation may differ among Docker Desktop releases, but the concepts correspond to the command-line checks.

For Windows users, remember that Docker Desktop may be connected to a Linux or Windows container engine. The exact startup command, shell syntax and file paths depend on the image’s operating system, not merely the host desktop. Our Virtual Machine Guide explains underlying isolation concepts without implying a Docker container is always equivalent to a full virtual machine.

A Safe Diagnostic Sequence You Can Reuse

Start with the name and intended purpose. Run docker ps -a, examine the exit code and OOMKilled state using docker inspect, and read recent docker logs. If Compose is involved, use docker compose ps -a, docker compose logs and docker compose config. Compare the effective command and entrypoint with the Dockerfile. Identify the first specific error before making any changes. Save sanitized results for a reproducible case.

Then check the relevant branch: successful one-time exit, missing runtime command, wrong path, permission error, dependency failure, memory pressure or an orchestrated stop. Apply one targeted correction at a time, test on a safe development or staging environment and confirm that the application performs its intended work. A running container is useful evidence, but a successful application health check and functional request are stronger evidence.

Diagram 2: Match The Fix To The Evidence
Normal Exit

No Fix Needed

Wrong Main Command

Correct Startup

Missing Configuration

Restore Setting

Permission Failure

Check Ownership

OOM Evidence

Investigate Memory

Original troubleshooting decision diagram. A status code alone does not establish a complete root cause.

Security And Data Preservation While Troubleshooting

Never turn off security controls, run untrusted repair scripts or publish access tokens to make an image start. Inspecting a container often reveals environment values, internal network names and file paths that should remain private. When copying logs into a support ticket, remove secrets, customer information and URLs containing credentials. Use the least privileged account suitable for troubleshooting.

Be especially cautious with commands that prune images, containers or volumes. Removing an unused-looking volume can permanently delete application data if backups are absent. Read our File System Guide for background on where data lives, and our Docker Storage Comparison before touching mounts. A reversible configuration check is preferable to destructive cleanup as a first response.

How To Verify The Repair Actually Worked

Once a targeted fix is applied, start a test container or the relevant Compose service and observe it for longer than the original failure interval. Check container status, logs and the application’s expected behavior. For a web server, send a legitimate local test request and verify the expected response; for a worker, confirm it processes a harmless test item; for a scheduled job, confirm that a clean exit is the intended outcome.

Record the working image version, startup command, relevant environment keys without exposing values, and the actual cause. Do not measure success only by whether a container remains Running. A sleeping process with a broken web service is not fixed, and a short-lived maintenance command that exits zero is not broken. Clear verification criteria prevent the same problem from returning during the next deployment.

Frequently Asked Questions

Why Does My Docker Container Exit Immediately?

Docker stops a container when its main process finishes or is terminated. The exit can be normal for a short job or indicate a startup error for a service. Inspect status, logs and the main command.

Does Exited With Code 0 Mean Docker Crashed?

No. Code zero generally means the main process finished successfully. Determine whether that application was intended to remain running.

What Does Docker Exit Code 137 Mean?

It commonly indicates SIGKILL. Memory pressure is one possible cause, but not the only one. Check the OOMKilled state, events and available memory evidence.

What Does Exit Code 143 Mean?

It commonly reflects SIGTERM and can be a normal controlled shutdown. Investigate the event that sent the termination signal.

How Can I See Logs After A Container Stops?

Run docker logs with the stopped container’s ID or name, provided the container still exists and its logging configuration supports that command.

Why Does My Container Restart Over And Over?

A failing startup process combined with an automatic restart policy can create a crash loop. Review logs and the effective command before changing restart behavior.

Should I Use Restart Always To Fix An Exiting Container?

Not automatically. Restart policies are useful for selected persistent services, but they do not repair a command that fails on every startup.

Can I Use Docker Exec In An Exited Container?

No. The standard docker exec command requires the target container to be running. Use logs, inspect and a safe diagnostic reproduction instead.

Can A Missing Volume Cause Immediate Exit?

Yes. The application may fail if a required file or writable path is missing or inaccessible. Verify mount settings and permissions without deleting data.

How Do I Know The Container Is Truly Fixed?

Verify the appropriate outcome: a service remains available and responds correctly, or a one-time task completes successfully. Check logs and application behavior, not status alone.

Scroll to Top

Discover more from XYZ Tech

Subscribe now to keep reading and get access to the full archive.

Continue reading