E-NO
Docker Restart Policies performance 13 Min Read

Docker Restart Policies and Performance Tuning: A Practical Guide

calendar_today Published: 2026-11-25
update Last Updated: 2026-11-25
analytics SEO Efficiency: 97%
Technical guide illustration for Docker Restart Policies and Performance Tuning: A Practical Guide.

Intro

Docker restart policies control whether containers automatically restart when they stop or crash. The default is no, meaning containers never restart on their own. Other policies include on-failure, always, and unless-stopped. Selecting the right policy and tuning its behavior significantly affects application availability, host resource consumption, and recovery time after failures.

In this guide, we explore how restart policies impact performance and provide practical tuning techniques. We cover how to select the right policy, configure restart delays and attempt limits where possible, combine policies with health checks for smarter restarts, and use resource limits to prevent restart storms. We include concrete commands, configuration snippets, and expected outputs for every major step, along with verification and rollback strategies.

By the end, you will be able to:

  • Inventory your Docker environment and current restart policy usage.
  • Choose the safest restart policy for different workloads.
  • Tune restart behavior using available options.
  • Diagnose restart loops and recover from failed configurations.
  • Follow a repeatable operations checklist for ongoing performance management.

Let's start with an environment inventory to establish a baseline.

Version and Environment Inventory

Before tuning restart policies, confirm your Docker engine version and inspect the current restart settings on existing containers. Docker's restart policy behavior has evolved; newer versions offer more features, such as the ability to set maximum retry count for on-failure.

Check your Docker version:

docker version --format '{{.Server.Version}}'

Expected output:

24.0.7

(Your version may differ; ensure it is at least 17.09 for full on-failure options, though recent versions are recommended.)

List all containers with their restart policy and status:

docker ps -a --format 'table {{.Names}}\t{{.Status}}\t{{.RestartPolicy}}'

Expected output (example):

NAMES     STATUS                            RESTART POLICY
web-app   Up 10 minutes                     always
cache     Exited (1) 2 minutes ago          no
worker    Restarting (1) 5 seconds ago      on-failure

Notice the Restarting status for the worker container, indicating it is within its restart loop. This may be a sign of a misbehaving application or an aggressive restart policy.

Inspect the detailed restart settings for a specific container:

docker inspect --format '{{.HostConfig.RestartPolicy}}' web-app

Expected output:

{on-failure 5}

If the output shows map[], the policy is effectively no. For a policy with maximum retry count, the format is {on-failure 5}.

Also inspect the Docker daemon configuration for any default restart policy overrides. Check /etc/docker/daemon.json (on Linux):

cat /etc/docker/daemon.json

Example daemon.json with no custom restart settings:

{
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m"
  }
}

If you have a custom default-restart-policy key, it applies to new containers unless overridden. Confirm its value.

Understanding your current configuration is the first step toward safe tuning.

Quick check 1 of 2

According to the passages, which restart policy is the default and does not restart the container under any circumstances?

The passage states that 'no' is the default restart policy and it does not restart the container under any circumstances.

Safe Configuration Path

When changing restart policies, always make changes in a controlled manner. For running containers, you can update the policy using docker update, but this does not apply to containers created with a different policy. If a container is currently running and you want to change its restart policy, use docker update --restart=<policy> without restarting the container. However, for more complex changes, it is often better to recreate the container with the desired options.

Choosing the Right Restart Policy

There are four restart policies:

PolicyBehaviorBest For
noNever restart automaticallyOne-off tasks, debugging
on-failure[:max-retries]Restart only on non-zero exit code, with optional max retriesBatch jobs, workers that fail on error
alwaysAlways restart, regardless of exit codeLong-running services like web servers
unless-stoppedAlways restart unless the container was explicitly stoppedSimilar to always, but respects manual stops

For performance-sensitive applications, avoid always for workloads that can crash loop due to configuration errors, as it can lead to rapid restart cycles consuming CPU and I/O. Use on-failure with a maximum retry count to bound the restart attempts and add restart delay to space them out.

Configuring on-failure with Max Retries

Docker allows you to specify a maximum retry count for on-failure using the restart policy syntax. For example:

docker run -d --restart=on-failure:5 myapp

Note: Docker does not have a built-in --restart-delay flag for standalone containers. To set a restart delay, you need to use Docker Compose (with a specific version) or an external process supervisor. In Docker Swarm mode, you can configure restart delays for services.

Create a container that fails and restarts up to 3 times:

docker run -d --name failing-test --restart=on-failure:3 alpine sh -c 'exit 1'

After a few seconds, inspect its status:

docker ps -a --filter name=failing-test

Expected output:

CONTAINER ID   IMAGE     COMMAND              CREATED          STATUS                     PORTS     NAMES
abc123def456   alpine    "sh -c 'exit 1'"     10 seconds ago   Exited (1) 8 seconds ago             failing-test

Although it may have restarted, after exceeding 3 attempts, Docker stops restarting it. The exact number of attempts and status may vary, but eventually it remains exited.

Using unless-stopped for Service Continuity

unless-stopped is similar to always but respects manual stops. This policy is recommended for production services because it allows you to intentionally stop a container without it restarting, while still auto-restarting after crashes or daemon restarts.

Run a web server with unless-stopped:

docker run -d --name web --restart=unless-stopped nginx:alpine

Stop the container:

docker stop web

Then check status:

docker ps -a --filter name=web

Expected output:

CONTAINER ID   IMAGE          STATUS                     PORTS     NAMES
...            nginx:alpine   Exited (0) 1 second ago              web

The container remains stopped because it was manually stopped. If you restart the Docker daemon, this container will not start automatically because it was stopped before the daemon restart.

Scoped Implementation Choices

When tuning restart policies for an existing application, start with one container or a small group. Use docker update to change policy on a running container if you don't want to recreate it. For example, change a running container from always to unless-stopped:

docker update --restart=unless-stopped web

This command returns immediately without output if successful. Verify with docker inspect.

For new deployments, define restart policies in your Docker run commands or Compose files. In Compose, specify under the service:

version: '3'
services:
  app:
    image: myapp:latest
    restart: unless-stopped

Then docker compose up -d applies the policy.

Remember, restart policies are ignored for containers run with --rm.

Verification and Diagnostics

After configuring restart policies, verify that they behave as expected and monitor for performance issues.

Inspect Restart Policy Details

Use docker inspect to view the restart policy of a container:

docker inspect --format '{{json .HostConfig.RestartPolicy}}' web | jq

Expected output:

{
  "Name": "unless-stopped",
  "MaximumRetryCount": 0
}

Monitor Restart Counts

Docker tracks the number of restarts for each container. Query this value:

docker inspect --format '{{.RestartCount}}' web

Example output:

2

A rapidly increasing restart count indicates a restart loop. Use docker stats to monitor resource consumption of restarting containers.

Simulate a Crash and Observe Behavior

To test a unless-stopped policy, kill the main process in the container:

docker exec web kill 1

Then immediately check status:

docker ps -a --filter name=web

Expected output:

CONTAINER ID   IMAGE          STATUS                  PORTS     NAMES
...            nginx:alpine   Up Less than a second             web

The container should have restarted automatically.

Diagnostic Commands for Restart Loops

If a container is stuck in a restart loop, view its logs to identify the cause:

docker logs --tail 50 web

Check the container's exit code history:

docker inspect --format '{{.State.ExitCode}}' web

If the exit code is non-zero, the application failed. If it's 0 but the container still restarts, it may be due to a health check failure (if configured) or another issue.

Health Checks to Prevent Unnecessary Restarts

Health checks allow Docker to determine if a container is healthy. A restart policy alone restarts on process exit, but a misbehaving container that remains running may not be restarted. By combining health checks with restart policies, you can detect unhealthy containers and take action. For standalone containers, use a wrapper like docker-autoheal or rely on external monitoring to restart containers when health checks fail. In Docker Swarm, service health checks trigger automatic replacement.

Define a health check in a Dockerfile:

FROM nginx:alpine
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 CMD curl -f http://localhost/ || exit 1

Build and run the image, then inspect health status:

docker run -d --name web-health --health-cmd="curl -f http://localhost/ || exit 1" --health-interval=10s nginx:alpine

Check health:

docker inspect --format '{{.State.Health.Status}}' web-health

Expected output:

healthy

If it transitions to unhealthy, Docker does not automatically restart it, but you can use a script or Swarm to act on it.

Analyzing Performance Impact of Restart Policies

Restart policies can affect host performance, especially during rapid restarts. Each restart consumes CPU, memory, and I/O. Monitor host metrics with docker stats for all containers:

docker stats --no-stream

Example output:

CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT     MEM %     NET I/O     BLOCK I/O
...            web       0.01%     2.1MiB / 1.952GiB     0.10%     1.2kB / 0B  0B / 0B
...            failing   0.00%     0B / 0B               0.00%     0B / 0B     0B / 0B

If you see high CPU spikes correlated with restart loops, consider adjusting the restart policy or the application's error handling.

Latency Checks for Recovery Time

Measure how long it takes a container to become ready after a restart. Use docker events to watch restart events and time with health checks to quantify recovery.

For example, record the time of a restart and then time until healthy:

docker events --filter 'container=web' --filter 'event=restart' --format '{{.Time}}' | head -1

Then, manually stop and start to measure:

time docker start web

This gives the startup time. For applications, also measure application-level readiness.

Failure Modes and Recovery

Restart policies can lead to problematic scenarios if not tuned properly. Understanding failure modes helps you recover quickly.

Restart Loop Caused by Application Error

If an application exits immediately due to a configuration error or missing dependency, always or unless-stopped will cause rapid restarts, potentially exhausting CPU and disk (due to logs).

Detection:

  • docker ps -a shows the container in Restarting state.
  • docker inspect --format '{{.RestartCount}}' container shows a high number.
  • Host CPU usage is elevated.

Recovery:

  • Stop the container to break the loop: docker stop container
  • Investigate logs: docker logs container
  • Fix the issue (e.g., environment variable, config file).
  • Adjust the restart policy to on-failure with a max retry count if appropriate.
  • Start the container again.

Exhausting Max Retry Count

With on-failure:3, after 3 failed attempts, the container remains stopped. This is desirable to avoid infinite loops, but you must monitor for containers that stopped due to exceeding retries.

Detection:

  • docker ps -a shows Exited (1) ... for the container.
  • docker inspect shows RestartCount equals the max retry count.

Recovery:

  • Fix the underlying issue.
  • Manually start the container: docker start container
  • If the issue recurs, reconsider the max retry count.

Unintended Restarts After Docker Daemon Restart

Containers with always will start automatically when the Docker daemon starts, even if they were manually stopped before the daemon restart (this is a known behavior difference from unless-stopped). If you stop a container and then restart the daemon, always containers will start.

Prevention: Use unless-stopped instead of always for services that should respect manual stops.

Restart Policy Not Applied Due to Orchestration Overrides

If you run containers within an orchestrator like Docker Swarm, Kubernetes, or Nomad, their restart policies may override Docker's container-level policy. For example, in Swarm, service restart policies are defined at the service level, not per container. Ensure you configure the policy in the orchestration tool.

Rollback Strategies

If a new restart policy causes issues, quickly revert:

  • For a single container, change back with docker update --restart=<original-policy> container.
  • If you recreated the container, you may need to stop and remove it, then run a new container with the previous policy.
  • In Compose, revert the restart directive and reapply with docker compose up -d.

Always document the previous configuration before making changes.

Quick check 2 of 2

What does the on-failure[:max-retries] restart policy do?

The passage states on-failure restarts the container if the exit code indicates an error and optionally limits the number of restart retries the Docker daemon attempts.

Common Pitfalls and How to Avoid Them

Here are frequent mistakes when working with Docker restart policies and practical ways to prevent or recover from them.

1. Using always for Containers That Crash Loop

Many users set --restart=always for every container, assuming it maximizes availability. However, if the application has a persistent error, it will restart indefinitely, consuming CPU, memory, and disk I/O, and flooding logs. This can degrade the entire host.

Why it happens: Misunderstanding the difference between always and on-failure. always restarts regardless of exit code, so even a container that exits with code 0 (e.g., a script that finishes) will restart.

How to avoid: Use unless-stopped for long-running services that should run continuously but respect manual stops. For batch jobs or workers, use on-failure with a reasonable max retry count. For example, --restart=on-failure:3 limits restarts to three attempts.

2. Ignoring Restart Counts and Logs

A container stuck in a restart loop often goes unnoticed until it affects system performance. Without monitoring, you may not realize that a service is repeatedly crashing.

Why it happens: Lack of visibility into container restart counts and status.

How to avoid: Regularly check restart counts with docker inspect --format '{{.RestartCount}}' <container> or use a monitoring tool. Set up alerts for containers exceeding a threshold (e.g., more than 5 restarts in 10 minutes).

3. Not Using Health Checks with Restart Policies

Restart policies only act on process exit. If a container remains running but is unhealthy (e.g., web server returns 500 errors), Docker will not restart it. This leads to undetected service degradation.

Why it happens: Assuming restart policies alone ensure application health.

How to avoid: Combine restart policies with health checks. Define a HEALTHCHECK in your Dockerfile or use --health-cmd when running the container. Then use an external tool like docker-autoheal or an orchestrator to restart unhealthy containers.

4. Setting Restart Policy on Containers Run with --rm

If you run a container with --rm and a restart policy, the restart policy is ignored because --rm removes the container when it exits. This can cause confusion when you expect automatic restarts.

Why it happens: Not understanding that --rm takes precedence over restart policies.

How to avoid: Avoid combining --rm with restart policies. If you need a temporary container, use --rm without restart. For persistent services, do not use --rm.

5. Not Considering Daemon Restart Behavior

Containers with always restart when the Docker daemon starts, even if they were manually stopped before the daemon restart. This can lead to unexpected containers running after a host reboot or Docker upgrade.

Why it happens: The always policy is designed to ensure containers are always running, so it overrides manual stops when the daemon restarts.

How to avoid: Use unless-stopped for services that should respect manual stops. If you must use always, be aware of this behavior and manually stop and remove containers if needed after daemon restarts.

Operations Checklist

Use this repeatable checklist to tune Docker restart policies safely and maintain performance. Assign an owner for each item and review quarterly or after any major application change.

Checklist ItemConcrete ExampleOwnerReview Frequency
Inventory current policiesRun docker ps -a --format 'table {{.Names}}\t{{.RestartPolicy}}\t{{.Status}}' on all hostsDevOps Engineer (e.g., Alex Johnson)Monthly
Identify high-churn containersQuery docker inspect --format '{{.RestartCount}}' <container> for all containers and flag those with >5 restarts in 24hSite Reliability Engineer (e.g., Priya Shah)Weekly
Select appropriate policy per workloadMap each container to a policy: no for one-off, on-failure:3 for batch, unless-stopped for servicesApplication Owner (e.g., Marcus Lee)Quarterly or on change
Apply changes in stagesChange one container's policy with docker update --restart=unless-stopped web and monitor for 24 hoursDevOps Engineer (Alex)As needed
Set resource limitsRun docker run -d --name limited --restart=always --memory=256m --cpus=0.5 myapp for new containersInfrastructure Lead (e.g., Sara Chen)On deployment
Implement health checksAdd HEALTHCHECK to Dockerfiles and verify with docker inspect --format '{{.State.Health.Status}}' containerApplication Developer (e.g., Tom Garcia)On build
Monitor restart counts and resource usageUse watch -n 5 'docker ps -a --format "table {{.Names}}\t{{.RestartCount}}\t{{.Status}}"' during incident responseSRE (Priya)Continuous during incidents, weekly otherwise
Document baseline and changesRecord current policies and changes in a config management repoDevOps Engineer (Alex)On change
Review regularlySchedule a quarterly audit of restart policies against application needsEngineering Manager (e.g., Linda Park)Quarterly

Example of applying resource limits with a restart policy:

docker run -d --name limited-service --restart=always --memory=256m --cpus=0.5 myapp

This limits the container to 256 MB memory and half a CPU core, preventing it from starving other processes even if it restarts frequently.

Example of a monitoring command to watch restart counts:

watch -n 5 'docker ps -a --format "table {{.Names}}\t{{.RestartCount}}\t{{.Status}}"'

This refreshes every 5 seconds and shows restart counts, helping you spot loops.

Conclusion

Tuning Docker restart policies is an essential part of maintaining reliable and efficient containerized applications. By selecting the right policy (preferring unless-stopped over always for services), using on-failure with retry limits for batch workloads, and combining policies with health checks and resource limits, you can avoid restart storms and reduce downtime.

Start with a narrow pilot: pick one container, adjust its restart policy, monitor the impact on restart frequency and resource usage, and then roll out changes to other services. Document your choices and create an operational checklist to regularly review your restart policies.

Remember, restart policies are a safety net, not a substitute for robust application error handling. Use them to complement a well-designed system, and continuously measure and tune for performance.

With the practical commands and diagnostic techniques in this guide, you are equipped to optimize Docker restart policies for your environment.

Related Research

Article Quality Score

Reader usefulness 97%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL