E-NO
Docker Restart Policies CI/CD 10 Min Read

Docker Restart Policies in CI/CD: A Practical Automation Guide

calendar_today Published: 2026-11-27
update Last Updated: 2026-11-27
analytics SEO Efficiency: 100%
Technical guide illustration for Docker Restart Policies in CI/CD: A Practical Automation Guide.

Intro

Docker restart policies are a simple but powerful mechanism to keep containers running during failures and reboots. In a CI/CD context, they affect how build agents, test runners, and deployment tools recover from crashes. However, a restart policy alone does not guarantee a healthy service. Without a matching healthcheck, rollback plan, and observability, automatic restarts can turn a small failure into a loop of repeated crashes.

This article is a practical guide for developers, DevOps consultants, and startup teams who run Docker in production or in pipelines. It connects restart policy configuration to deployment workflows, pipeline automation, and rollback decisions. You will learn how to observe container state, choose the right restart policy for each workload, verify that restarts actually work, and recover when a container gets stuck in a restart loop. The focus is operational safety: observe before changing, limit blast radius, use placeholders instead of secrets, verify results, and document recoveries.

By the end, you will be able to answer questions like: Should my database container use always or unless-stopped? How do I test a restart policy before deploying to production? What signals tell me a restart loop is happening? And how do I roll back a bad update when the container keeps restarting?

How Docker Restart Policies Work

Docker applies a restart policy when a container exits. The daemon checks the policy and decides whether to restart the container, and how long to wait before attempting another restart. Docker implements restart policies in the engine, not in the container itself. This means the policy works even if the application inside the container crashes or the OOM killer terminates it.

Docker supports four restart policies: no, on-failure, always, and unless-stopped. The default is no, which means Docker will never restart the container automatically. Choosing the right policy depends on the workload and how the container is managed.

Policy reference and behavior

  • no: Docker never restarts the container. Use this for one-shot jobs like database migrations or build steps in a CI pipeline. If the job fails, you want the pipeline to fail, not to restart the job silently.
  • on-failure[:max-retries]: Docker restarts the container only if it exits with a non-zero code. You can optionally set a maximum number of retries by adding a colon and a number, for example on-failure:5. This is useful for services that may crash occasionally but should not restart forever. After the maximum number of retries, Docker gives up and leaves the container stopped.
  • always: Docker restarts the container regardless of the exit code, even if it exits with code 0. This is suitable for long-running daemons like web servers or message brokers. Note that always does not restart a container that was manually stopped with docker stop; it only applies to unexpected exits.
  • unless-stopped: Similar to always, but Docker will not restart the container after the daemon restarts if the container was previously stopped manually. This policy is often preferred for production services because it respects manual intervention.

A common mistake is to use always for a service that sometimes exits normally, for example a worker that finishes processing a queue and exits with code 0. With always, Docker will restart that worker again and again, causing unnecessary load. Use on-failure for services that should exit cleanly, and always or unless-stopped only for services that should run indefinitely.

How restart policies interact with Docker Compose and Swarm

Docker Compose supports restart policies through the restart key in a service definition. For example:

services:
  web:
    image: nginx:1.25
    restart: unless-stopped
    ports:
      - "80:80"

In Docker Swarm, restart policies work differently. Swarm services do not use the same restart mechanism; instead, the orchestrator manages replication and restarts containers according to the desired state. Swarm uses restart_policy under deploy in a stack file, with additional options like condition, delay, and max_attempts. For standalone Docker, the standard restart policies apply.

Choosing a Restart Policy for CI/CD Workloads

Different components in a CI/CD system have different restart needs. Here is a decision table for common workloads:

WorkloadRecommended policyWhy
CI runner (ephemeral)no or on-failure:3A runner that is created per job should exit when the job finishes. Restarting it would run the job again, which is rarely what you want. If the runner crashes mid-job, a few retries may be acceptable, but after that the pipeline should fail and alert a human.
Build cache serverunless-stoppedThe cache server should be available as long as the host is up, but if an operator manually stops it for maintenance, Docker should not resurrect it until explicitly started.
Database for integration testson-failure:5During testing, a database may crash due to bad queries. A few automatic restarts can keep the test suite moving, but persistent crashes should stop the pipeline and fail the build.
Long-running service (e.g., web app, API)unless-stoppedThe service should always be up unless deliberately stopped. This is the safest choice for production services because it respects manual intervention during maintenance.
Monitoring agent (e.g., Prometheus node exporter)alwaysThe agent should never stay down. Even if it exits with code 0 unexpectedly, you want it restarted immediately.

These are starting points, not strict rules. Always consider the consequences of a restart loop. For example, a database with unless-stopped that crashes due to a corrupt data file will restart repeatedly, potentially causing more damage. Pair the restart policy with a healthcheck and an alerting rule to catch such loops.

Configuring Restart Policies in Practice

Docker CLI

To set a restart policy when running a container, use the --restart flag:

docker run -d --name api --restart unless-stopped -p 8080:80 myapi:1.2.0

After creating the container, inspect its restart policy:

docker inspect api --format '{{.HostConfig.RestartPolicy.Name}} {{.HostConfig.RestartPolicy.MaximumRetryCount}}'

Expected output for the above command:

unless-stopped 0

The MaximumRetryCount is 0 because unless-stopped does not have a retry limit.

To change the restart policy of an existing container, you must recreate it. Docker does not allow changing restart policy on a running container. For example:

docker stop api
docker rm api
docker run -d --name api --restart on-failure:5 -p 8080:80 myapi:1.2.0

Docker Compose

In a Compose file, set the restart policy under each service:

services:
  api:
    image: myapi:1.2.0
    restart: on-failure:5
    ports:
      - "8080:80"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 5s
      retries: 3
      start_period: 10s

After updating the file, run:

docker compose up -d

Compose will recreate only the services whose configuration changed. To force recreation of a specific service:

docker compose up -d --force-recreate api

Docker Swarm

In a Swarm stack file, use the deploy section:

services:
  api:
    image: myapi:1.2.0
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s
    ports:
      - "8080:80"

Parameters:

  • condition: none, on-failure, or any (always).
  • delay: time to wait between restart attempts.
  • max_attempts: maximum number of restarts before giving up.
  • window: time window during which restart attempts are counted.

Apply the stack:

docker stack deploy -c stack.yml mystack

Quick check 1 of 2

Which restart policy is the default when none is specified for a container?

Passage 1 states that `no` is the default restart policy, which does not restart the container under any circumstances.

Observing Restart Behavior and Health

A restart policy is only meaningful if you can observe its effects. Use the following commands to check container state, logs, and restart counts.

Check current status

docker ps -a --format "table {{.Names}}\t{{.Status}}\t{{.RestartCount}}\t{{.Image}}"

Example output:

NAMES     STATUS                          RESTART COUNT   IMAGE
api       Up 10 minutes (healthy)         2               myapi:1.2.0
worker    Restarting (1) 5 seconds ago    7               worker:latest

The worker container is in a restart loop: it has restarted 7 times and is currently in the process of restarting again. This is a red flag that the application is crashing immediately after start.

View logs around restarts

To see why a container keeps restarting, inspect its logs. The --since flag can help focus on recent attempts:

docker logs worker --tail 50 --since 5m

If the container exits too quickly to view logs while it is running, use docker logs after the container has stopped. Docker retains logs for stopped containers unless they are removed.

Inspect restart policy and state

For more detail:

docker inspect worker --format '{{json .State}}' | jq .

Key fields include Status, Running, Restarting, ExitCode, Error, OOMKilled, and Dead. If Restarting is true and ExitCode is non-zero, the container is in a restart loop.

Healthchecks and restart policies

Restart policies act on container exit. Healthchecks act on application health. A container can be running but unhealthy, and Docker will not restart it unless it actually exits. To automatically restart unhealthy containers, you need an external orchestrator or a tool like autoheal. For standalone Docker, you can use the following pattern in a script or CI step:

# Check health status and restart if unhealthy
if [ "$(docker inspect --format='{{.State.Health.Status}}' api)" = "unhealthy" ]; then
  docker restart api
fi

But this is reactive. Better to fix the root cause. In CI/CD, use docker compose up --exit-code-from for services that must pass a health check before proceeding.

Testing Restart Policies Before Production

You can safely test restart policies on a local Docker host or in a CI job. The goal is to simulate crashes and verify that Docker restarts the container as expected.

Test with a container that exits

Create a container that exits immediately with a non-zero code:

docker run -d --name crash-test --restart on-failure:3 busybox sh -c "exit 1"

Wait a few seconds and then check the restart count:

docker inspect crash-test --format '{{.RestartCount}}'

After 3 restarts, Docker should stop trying and leave the container in Exited state. Check:

docker ps -a --filter name=crash-test --format '{{.Status}}'

Expected output shows Exited (1) ... and RestartCount should be 3.

Test with a command that hangs

For always or unless-stopped, use a container that runs indefinitely, then kill it manually:

docker run -d --name long-run --restart unless-stopped busybox sleep 300
sleep 2
docker kill long-run
sleep 2
docker ps -a --filter name=long-run --format '{{.Status}}'

You should see the container in Up state again. If not, inspect the restart policy:

docker inspect long-run --format '{{.HostConfig.RestartPolicy.Name}}'

Include restart tests in CI

A CI pipeline can include a job that runs a container with a restart policy, simulates a crash, and asserts the restart count. For example, in a GitLab CI job:

restart-policy-test:
  stage: test
  script:
    - docker run -d --name crash-test --restart on-failure:3 busybox sh -c "exit 1"
    - sleep 10
    - test "$(docker inspect crash-test --format '{{.RestartCount}}')" = "3"
  after_script:
    - docker rm -f crash-test

If the assertion fails, the pipeline fails, alerting you that restart behavior is not as expected.

Common Pitfalls and How to Avoid Them

Several mistakes can turn a restart policy from a safety net into a source of instability. Here are the most frequent pitfalls and how to recover from them.

Restart loop for data stores

Pitfall: A database container with always or unless-stopped restarts endlessly because of a corrupt data file. Each restart may attempt recovery, fail, and restart again, generating high CPU and I/O.

Why it happens: The restart policy cannot distinguish between a transient error and a permanent corruption. Once the exit code is non-zero, Docker retries indefinitely.

How to recover: Detect the loop early (via restart count and logs). Stop the container manually: docker stop db. Fix the data or restore from a backup. Then restart. To prevent recurrence, use on-failure:5 for stateful services, so Docker gives up after a few attempts and you get an alert instead of a load spike.

Restarting one-shot jobs

Pitfall: A database migration or batch job is run with docker run --restart always. The job completes, exits with code 0, and Docker immediately restarts it, running the migration again. This can corrupt data or cause duplicate records.

Why it happens: always restarts regardless of exit code. The operator wanted resilience but applied it to a job that should run once.

How to avoid: Use --restart no (default) for one-shot jobs. If the job must be retried on failure, use --restart on-failure:2 and let the pipeline handle final failure.

Ignoring manual stops with always

Pitfall: An operator runs docker stop on a container to perform maintenance, but the container is immediately restarted by Docker because the policy is always and the manual stop exited with code 0? Actually, always does not restart a manually stopped container. Wait, is that correct? Let's clarify: According to Docker docs, always policy means the container will always restart if it stops. However, if the container is manually stopped, its restart policy is not triggered until Docker daemon restarts or the container is manually started again. So manual stop does not cause immediate restart unless the daemon restarts. But if the daemon restarts, always will restart the container even if it was manually stopped, whereas unless-stopped will not. This difference is subtle and often misunderstood.

Pitfall: Using always for a service that should stay stopped after manual intervention across daemon restarts. For example, an operator stops a service for patching, reboots the host, and the service comes back unexpectedly.

Why it happens: always does not remember that the container was manually stopped before the daemon restarted.

How to avoid: Use unless-stopped for most production services. It restarts on unexpected exits but remains stopped if the operator manually stopped it, even after a daemon restart.

Restart policy without healthcheck

Pitfall: A container is running but the application inside is unresponsive (e.g., deadlock). Docker does not restart it because the container has not exited. The service appears up but serves errors.

Why it happens: Restart policies only react to container exit codes, not to application health.

How to avoid: Always define a healthcheck for long-running services, and use an external process to restart unhealthy containers if needed. In Swarm, you can configure healthcheck and restart_policy together, but Swarm does not automatically restart unhealthy tasks unless they exit. Consider using a process supervisor inside the container or an external monitoring tool.

Misunderstanding on-failure retry count

Pitfall: Setting --restart on-failure:5 and expecting Docker to make 5 restart attempts after each failure forever. In practice, after the container restarts successfully and runs for a while, the retry counter resets only if the container exits with code 0? Actually, Docker documentation says the maximum retry count applies only to consecutive failures. If the container runs successfully for a period of time (default 10 seconds?) and then fails again, the count resets. But the exact behavior is not well documented and may vary by version. Some users report that retries reset only on manual restart or daemon restart.

Why it happens: Users assume the retry count is absolute, not consecutive.

How to avoid: Test the behavior with a script before relying on it. Use a small script that exits non-zero, then after a few restarts, exits zero, then non-zero again, and observe the restart count. Adjust your expectations accordingly.

Automating Restart Policy Management in CI/CD Pipelines

In a CI/CD pipeline, you often need to ensure that services are started with the correct restart policy. You can manage this with configuration as code: define the desired state in Docker Compose or Kubernetes manifests, and have the pipeline apply it.

Example: Deploy a web service with Ansible and Docker Compose

Suppose you have a Compose file docker-compose.prod.yml:

version: "3.8"
services:
  web:
    image: registry.example.com/webapp:${IMAGE_TAG}
    restart: unless-stopped
    environment:
      DATABASE_URL: ${DATABASE_URL}
      SECRET_KEY: ${SECRET_KEY}
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health"]
      interval: 30s
      timeout: 5s
      retries: 3
    deploy:
      resources:
        limits:
          cpus: "0.50"
          memory: 512M

In your CI pipeline, after building and pushing the image, you can run:

export IMAGE_TAG=$CI_COMMIT_SHA
export DATABASE_URL=$(vault kv get -field=url secret/database)
export SECRET_KEY=$(vault kv get -field=key secret/webapp)
docker compose -f docker-compose.prod.yml up -d

If you are using a cluster, you might use docker stack deploy instead. The key is that the restart policy is part of the declarative configuration, so every deployment enforces the same policy.

Validating restart policy before deployment

As part of your CI, you can add a validation step that checks the restart policy of the created container matches the desired value. For example:

docker compose -f docker-compose.prod.yml up -d --no-start web
actual_policy=$(docker inspect web --format '{{.HostConfig.RestartPolicy.Name}}')
expected_policy="unless-stopped"
if [ "$actual_policy" != "$expected_policy" ]; then
  echo "Restart policy mismatch: expected $expected_policy, got $actual_policy"
  exit 1
fi

This step starts the container without actually running it, inspects the policy, and fails the pipeline if it is wrong. Then you can start the container normally.

Rollback when restarts cause instability

If a new deployment causes restart loops, you need to roll back quickly. Because the restart policy is tied to the container, rolling back means stopping the bad container and starting a new one from a previous image version.

For instance, if you tagged the previous good image as webapp:1.4.2 and the new as webapp:1.5.0, and after deployment the new container is restarting repeatedly, you can:

# Stop the bad container
docker stop webapp_1.5.0
# Start a new container with the old image and same policy
docker run -d --name webapp_1.4.2 --restart unless-stopped \
  --env-file .env.prod \
  -p 80:80 registry.example.com/webapp:1.4.2

But the ideal approach is to use a container orchestrator or a load balancer that can shift traffic to a healthy instance. In a Docker Swarm, for example, you can roll back a service:

docker service update --rollback webapp

This reverts to the previous service specification, including restart policy.

Quick check 2 of 2

With the `on-failure[:max-retries]` policy, under what condition does the platform restart the container?

Passage 1 describes `on-failure[:max-retries]` as restarting the container if the exit code indicates an error, optionally limiting the number of retries.

Monitoring and Alerting for Restart Loops

Restart loops are a common failure mode, and you should monitor for them. The simplest metric is the container restart count, which Docker exposes in many monitoring tools.

If you use Prometheus, you can use the container_last_seen or container_start_time_seconds metrics, but for restart count, you can use the container_restart_count metric if your Docker monitoring tool exports it. Many exporters, like cadvisor, provide container_restart_count.

Example PromQL alert rule for restart loops:

groups:
- name: docker
  rules:
  - alert: ContainerRestartLoop
    expr: increase(container_restart_count{name=~"webapp.*"}[10m]) > 5
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Container {{ $labels.name }} is in a restart loop"
      description: "Container {{ $labels.name }} has restarted more than 5 times in the last 10 minutes."

This alert fires when any container matching webapp.* restarts more than 5 times in 10 minutes. The for: 5m ensures the condition persists before alerting.

Log-based detection

If you don't have metrics, you can monitor Docker events for restart actions:

docker events --filter 'event=restart' --filter 'container=webapp' --since 10m

This prints a line each time the container restarts. In a script, you can count events and trigger an alert.

Data Persistence and Restart Policies

Restart policies do not affect data persistence, but data persistence affects how well a restart policy works. If a container writes to its own filesystem and restarts, the data is gone. For stateful services, always use named volumes or bind mounts.

Example for a PostgreSQL container:

services:
  db:
    image: postgres:16
    restart: unless-stopped
    volumes:
      - db_data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
  db_data:

Now, when the container restarts, the data persists. Test this by stopping and starting the container:

docker compose stop db
docker compose start db

Then verify data is still accessible. If the data disappears, you were likely writing to the container's ephemeral filesystem.

Operations Checklist for Managing Restart Policies

Use this checklist when you need to change or verify a restart policy on a production service.

StepResponsible ownerActionVerificationRevisit frequency
1. Identify current policyOn-call DevOps engineer (e.g., Priya Shah)Run docker inspect <container> --format '{{.HostConfig.RestartPolicy.Name}} {{.HostConfig.RestartPolicy.MaximumRetryCount}}'Output matches expected policy from service catalogAt each deployment
2. Observe current restart count and healthOn-call engineerRun docker inspect <container> --format '{{.RestartCount}} {{.State.Health.Status}}'RestartCount < threshold (e.g., <5 in last hour), Health.Status = healthyContinuous monitoring
3. Change restart policy (if needed)Service owner (e.g., DevOps Lead)Recreate container with new --restart flag or update Compose file and run docker compose up -dPolicy is applied after recreation. Confirm with step 1.On request, with change ticket
4. Test restart behaviorQA engineerSimulate crash by docker kill -s KILL <container> or force exit with docker exec <container> kill 1Container restarts within expected time (e.g., 10 seconds). RestartCount increments by 1.Before each production release
5. Verify data persistenceService ownerAfter restart, run application-specific data integrity check (e.g., docker exec db psql -c 'SELECT count(*) FROM users;')Count matches baseline (e.g., 1000 rows)Before each production release
6. Check monitoring alertsMonitoring adminEnsure Prometheus or other tool is receiving container_restart_count metric and alerts are configured.Alert fires in test environment when restart threshold exceeded.Monthly audit
7. Document rollback planTeam leadWrite runbook for rolling back image version and restart policy if loops occur. Include commands and decision criteria.Runbook is reviewed and tested in a staging failover drill.Quarterly or after major changes

Single accountable owner: For the overall restart policy strategy, the DevOps Lead (or equivalent) owns the decision to change default policies. That person reviews the policy set quarterly and after any major incident.

Conclusion

Docker restart policies are a small but critical part of container reliability. In CI/CD pipelines, they help build agents and test services recover from transient failures, but they must be paired with healthchecks, monitoring, and rollback plans to avoid restart loops. By observing current state, choosing the right policy per workload, validating policies in CI, and automating recovery, you can use restart policies to increase uptime without masking deeper issues.

Start with one low-risk verification: pick a service, check its restart policy and restart count, simulate a crash in a test environment, and confirm the policy behaves as expected. Then document the rollback procedure. These small steps make your container infrastructure more predictable and easier to operate.

A reliable technical workflow makes failure visible, protects sensitive values, limits changes to the intended resource, and defines recovery verification before an incident forces the decision. Docker restart policies, when used correctly, are an essential tool in that workflow.

Related Research

Article Quality Score

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