You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker Swarm服务创建失败后条目是否保留?如何自动移除?

Docker Swarm Service Failure Behavior & Auto-Removal Solutions

Let’s break down your questions with practical, straight-to-the-point answers:

1. Will REPLICAS always show 0/1 if a service’s container fails to start?

Yep, that’s the standard behavior. When you create a service with a desired replica count (like 1), Docker Swarm tracks both the desired and running replica numbers. If the container can’t start—say due to a bad config, missing image, or dependency issue—the running count drops to 0, so REPLICAS will display as 0/1.

Even with --restart-max-attempts=1, once Swarm uses up its restart tries, it stops attempting to spin up the container. But the service’s desired state stays set to 1, so the REPLICAS value remains 0/1—Swarm still "knows" you wanted that service to exist, even if it can’t run successfully.

2. Does the service entry stay in the service list with --restart-max-attempts=1?

Absolutely. Docker Swarm never automatically removes services that fail to start, no matter what restart policy you set. The service definition is stored in the cluster’s raft database, so it’ll stick around in docker service ls until you manually delete it with docker service rm <service-name>.

3. Is there a way to automatically remove failed service entries?

Swarm doesn’t have a built-in feature for this, but you can set up a custom solution with scripts and scheduled tasks:

Option 1: Bash Script + Cron Job

Create a script that scans for services with 0 running replicas (but a desired count greater than 0) and deletes them:

#!/bin/bash
# Fetch services where desired replicas > 0 but running replicas = 0
failed_services=$(docker service ls --format "{{.ID}} {{.Replicas}} {{.Name}}" | grep -E "0/[1-9]+")

for service in $failed_services; do
  service_id=$(echo $service | awk '{print $1}')
  service_name=$(echo $service | awk '{print $3}')
  echo "Removing failed service: $service_name (ID: $service_id)"
  docker service rm $service_id
done

Save this as cleanup-failed-services.sh, make it executable (chmod +x cleanup-failed-services.sh), then add it to a cron job to run at your preferred interval (e.g., every 10 minutes).

Option 2: Run the Script as a Swarm Service

To make this cluster-wide, package the script into a small Docker image (using an alpine base with Docker CLI installed) and deploy it as a periodic Swarm service. You can add basic scheduling with a sleep loop in the container, or use open-source cron-style tools built for Swarm. Just make sure the service has access to the Docker socket (mount /var/run/docker.sock into the container) so it can run docker service commands.


内容的提问来源于stack exchange,提问作者Xianyi Ye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:46:50