Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 52 of 8021. Container FundamentalsFree lesson

Automating Container Restarts After Failure

Configure restart policies to ensure containers automatically recover from crashes or unexpected process exits.

In this lesson, you will learn how to make your containers self-healing by configuring restart policies that automatically recover from unexpected crashes.

Why Containers Fail

Even with the best code, containers can stop unexpectedly. Perhaps your application runs out of memory, encounters a bug that triggers a crash, or the underlying daemon experiences a momentary hiccup. Without a restart policy, a crashed container simply stays in the exited state, requiring you to manually intervene and run docker start to get your service back online.

Automating Recovery with Restart Policies

Docker provides a --restart flag that acts as a simple watchdog. When you run a container, you can instruct the Docker daemon to monitor the process and take action if it stops.

The most common policy for production environments is always. This tells Docker to restart the container regardless of why it stopped (even if you explicitly stop it, it will start again upon the next daemon reboot).

Consider this command:

docker run -d --restart always nginx

If the nginx process inside this container crashes, the Docker daemon detects that the process has exited with a non-zero code. Because of the always policy, the daemon immediately schedules the container to restart.

Choosing the Right Policy

You have a few options for these policies:

  • --restart no: (Default) The container will not restart automatically.
  • --restart on-failure: The container restarts only if it exits due to an error (a non-zero exit code).
  • --restart always: The container always restarts if it stops, even if you manually stopped it.
  • --restart unless-stopped: Similar to always, but it won't restart the container if you have manually stopped it before the daemon restarts.

By setting these policies, you move from "manual maintenance" to "automated resilience." Your infrastructure becomes significantly more robust because it handles minor transient failures without needing you to wake up at 3:00 AM to type a command.

Key Takeaway: By configuring a restart policy, you delegate the responsibility of container recovery to the Docker daemon, ensuring your services stay online even after a crash.