Automatic restart container when using docker-compose unless stopped

When using docker run for a single container using the restart policy, we can control the crashed container to restart based on condition. Using a --restart flag in docker run command as below to restart the container and configures it to always restart unless it is explicitly stopped or Docker is restarted:

$  docker run -d --restart unless-stopped apache

Here are the list of flags for the --restart option:

Flag Description
no Do not automatically restart the container. (the default)
on-failure[:max-retries] Restart the container if it exits due to an error, which manifests as a non-zero exit code. Optionally, limit the number of times the Docker daemon attempts to restart the container using the :max-retries option.
always Always restart the container if it stops. If it is manually stopped, it is restarted only when Docker daemon restarts or the container itself is manually restarted. (See the second bullet listed in restart policy details)
unless-stopped Similar to always, except that when the container is stopped (manually or otherwise), it is not restarted even after Docker daemon restarts.

And this command will ensure all currently running containers will be restarted unless stopped

$ docker update --restart unless-stopped $(docker ps -q)

For docker-compose can use the same --restart flag in each container level as below:

version: '2'
services:
  web:
    build: .
    restart: always         # <--- my addition 
    depends_on:
      - db
      - apache
  apache:
    image: apache
  db:
    image: postgres

Here are the different levels of --restart flag usage

version: “3.6”
     restart: always <-- here at top level?
services:
    restart: always <-- or here at services level ?
web:
…web parameters
    restart: always <-- or perhaps in each service, here?

database:
…database parameters
    restart: always <-- or perhaps in each service, here?

Note: With docker-compose, the “restart:” node is a direct child node of a specific service, a sibling of “image:” For Swarm stack deploymets, the “restart_policy:” node is a child node of “deploy:”, which itself is a sibling of “image:”

Courtesy: Docker forum

Facebook Facebook Twitter Reddit

Leave a Reply