如何在Linux下关闭虚拟机时停止docker

问题描述 投票:0回答:1

我有 3 个 dockers 容器正在运行,我想在关闭虚拟机之前停止容器。

我创建一个文件:/etc/systemd/system/unmount-disks.service

[Unit]
Description=Démontage des disques externes et NAS avant arrêt
DefaultDependencies=no
Before=docker.service shutdown.target reboot.target halt.target

[Service]
Type=oneshot
ExecStart=/usr/local/bin/unmount_disks.sh
RemainAfterExit=true
Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

[Install]
WantedBy=halt.target reboot.target shutdown.target

然后是 /usr/local/bin/unmount_disks.sh :

#!/bin/bash

# Arrêter tous les conteneurs sauf GitLab Runner et Portainer Agent

for CONTAINER in $(docker ps -q); do
    CONTAINER_NAME=$(docker inspect --format '{{.Name}}' $CONTAINER | sed 's/\///g')
    echo "Traitement du conteneur : $CONTAINER_NAME..."

    if [ "$CONTAINER_NAME" == "gitlab-runner" ] || [ "$CONTAINER_NAME" == "portainer_agent" ]; then
        echo "Conteneur $CONTAINER_NAME ignoré..."
    else
        echo "Arrêt du conteneur $CONTAINER_NAME..."
        docker stop $CONTAINER
    fi
done

但是我有这个错误:

-- Boot 0a7bed5f09ac4ab1b414124571f070cc --
oct. 06 08:23:06 cicd systemd[1]: Starting Démontage des disques externes et NAS avant arrêt...
oct. 06 08:23:07 cicd unmount_disks.sh[2979]: error during connect: Get "http://%2Fvar%2Frun%2Fdocker.sock/v1.47/contai>
 externes et NAS avant arrêt.

docker 服务似乎在我的脚本之前关闭了?

如果我在 root 下手动运行脚本,一切正常。

linux docker
1个回答
0
投票

这就是我所做的:

创建您的脚本服务,

/etc/systemd/system/myservice.service

包含以下内容:

[Unit]
Description:myservice
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=/usr/local/bin/unmount_disks.sh

[Install]
WantedBy=multi-user.target
© www.soinside.com 2019 - 2024. All rights reserved.