How to automate container stop/start?

I am using Portainer to manage Docker containers, and I have deployed a stack named XYZ (comprising 4 containers). I need to take a backup of the entire stack, and the entire stack needs to be stopped while the backup is running. How can I automate the stop and start of the entire stack?

Thanks :slight_smile:

Since I’m using Portainer Community Edition to manage my containers, I couldn’t find any useful features. So, I had to remove the Immich from Portainer and redeploy it in Qnap Container Station. The rest of the process is done using shell scripts and Qnap storage snapshots. The scripts are scheduled to run via crontab. Here are the scripts and the steps involved:

1. Create a script to stop the Immich stack:

#!/bin/bash
#
# Stops containers to take a QNAP snapshot
#

# Set PATH so QNAP docker binary is found
export PATH=/share/ZFS530_DATA/.qpkg/container-station/bin:$PATH
export HOME=/root

# Optional: use full path to be 100% sure
DOCKER_BIN=/share/ZFS530_DATA/.qpkg/container-station/bin/docker

# Stop all Immich containers
$DOCKER_BIN stop $($DOCKER_BIN ps -q --filter "name=Immich")

2. Create a script to start the Immich stack:

#!/bin/bash
#
# Stops containers to take a QNAP snapshot
#

# Set PATH so QNAP docker binary is found
export PATH=/share/ZFS530_DATA/.qpkg/container-station/bin:$PATH
export HOME=/root

# Optional: use full path to be 100% sure
DOCKER_BIN=/share/ZFS530_DATA/.qpkg/container-station/bin/docker

# Start all Immich containers
$DOCKER_BIN start $($DOCKER_BIN ps -a -q --filter "name=Immich")

if you need to add the bridge network to the Immich-Server container, so it is accessible via Cloudflare, add the following to the bottom of the start script:

# Wait 30 seconds
sleep 30

# Add bridge network to the Immich-Server container
$DOCKER_BIN network connect bridge Immich-Server

3. Create crontab entry for the stop and start scripts:

0 1 * * * /bin/sh /share/Scripts/Qnap/stop_containers.sh >> /share/Scripts/Logs/crontab_stop_container.log 2>&1
5 1 * * * /bin/sh /share/Scripts/Qnap/start_containers.sh >> /share/Scripts/Logs/crontab_start_container.log 2>&1

4. Create a scheduled snapshot that matches the start/stop scripts time in the crontab

Optional: Replicate your snapshot to another NAS.

I hope someone finds this helpful. :slight_smile:

1 Like

I also found this article about starting containers automatically.

1 Like