在 docker-compose.yml 文件中,restart 选项用于指定 Docker 容器的重启策略,以便在容器退出或失败时自动重启它。这个选项非常有用,特别是在生产环境中,可以提高服务的可用性和可靠性。


重启策略选项

Docker 支持以下几种重启策略:


no:默认值,不会自动重启容器。

always:总是重启容器,无论退出状态如何。

on-failure:仅当容器以非零退出代码停止时才重启。

unless-stopped:总是重启容器,除非容器被手动停止或 Docker 服务被停止。


基本语法

在 docker-compose.yml 文件中,restart 选项位于服务定义下。例如:


version: '3.8'

services:
  web:
    image: nginx:latest
    ports:
      - "80:80"
    restart: always

  app:
    build: ./app
    ports:
      - "5000:5000"
    restart: on-failure

  db:
    image: postgres:13
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=mydatabase
      - POSTGRES_USER=user
      - POSTGRES_PASSWORD=secret
    restart: unless-stopped

volumes:
  db-data:
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.

示例使用

restart: no

这是默认设置,即使未显式设置 restart 选项,容器也不会自动重新启动。


services:
  example-no-restart:
    image: someimage
    restart: no
restart: always
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

无论容器的退出状态如何,总是自动重启容器。


services:
  example-always-restart:
    image: someimage
    restart: always
restart: on-failure
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.


仅在容器因错误而退出时重新启动(退出代码不为 0)。


services:
  example-on-failure:
    image: someimage
    restart: on-failure
  • 1.
  • 2.
  • 3.
  • 4.

你还可以指定最大重启次数,例如最多重试 5 次:


services:
  example-on-failure-with-max-retries:
    image: someimage
    restart: on-failure
    deploy:
      restart_policy:
        condition: on-failure
        max_attempts: 5
restart: unless-stopped
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.


容器将始终重启,除非它们被手动停止或 Docker 服务被停止。


services:
  example-unless-stopped:
    image: someimage
    restart: unless-stopped
  • 1.
  • 2.
  • 3.
  • 4.

使用场景

开发环境:


在开发环境中,你可能希望手动控制容器的生命周期,因此可以使用 restart: no。

测试/预生产环境:


在这些环境中,当某些服务需要高可用性时,可以使用 restart: on-failure,以确保在服务崩溃后自动重启。

生产环境:

在生产环境中,通常会使用 restart: always 或 restart: unless-stopped 来确保服务的持续可用性。

结合其他选项

在一些复杂场景中,你可能希望与其他选项结合使用,例如健康检查和重启策略:


services:
  app:
    image: myapp:latest
    restart: on-failure
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 1m30s
      timeout: 10s
      retries: 3
    deploy:
      restart_policy:
        condition: on-failure
        delay: 5s
        max_attempts: 3
        window: 120s
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

总结

restart 选项用于设置 Docker 容器的重启策略,以提高服务的可用性和可靠性。

常用的重启策略包括 no, always, on-failure, 和 unless-stopped。

不同的策略适用于不同的环境和使用场景,如开发、测试、预生产、和生产环境。

可以结合其他选项如健康检查和部署策略来实现更复杂的配置。


通过正确配置重启策略,你可以显著提高应用的稳定性和可用性。