skip to Main Content

I have 3 dockers container running, and i want stop container before shutdown the vm.

I create one file : /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

and then the /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

But i have this error :

-- Boot 0a7bed5f09ac4ab1b414124571f070cc --
unmount_disks.sh[3685]: error during connect: Get "http://%2Fvar%2Frun%2Fdocker.sock/v1.47/containers/json": EOF

It seems the docker service is shutdown before my script ?

If i run the script under root manually, everything is working.

2

Answers


  1. Chosen as BEST ANSWER

    Ok got it working with :

    Requires=docker.service
    After=docker.service
    Before=shutdown.target reboot.target halt.target
    

    And in my script :

    export DOCKER_HOST=unix:///var/run/docker.sock
    

  2. Here is what I do:

    Create your script service,

    /etc/systemd/system/myservice.service

    containing the following:

    [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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search