Create Docker-Compose files from your Docker containers

A simple script that will create Docker-Compose files of your active containers so that you can back them up or use them on another server to re-create your containers.

Create Docker-Compose files from your Docker containers

I found this on Reddit recently - it's a simple bash script that runs through all your active Docker containers and creates Docker-Compose files for them. Very useful for creating Docker-Compose files for back up purposes without having to create them manually.

The repository can be found here:

danmed/Docker-Compose-Backup
Create compose files from running containers. Contribute to danmed/Docker-Compose-Backup development by creating an account on GitHub.

How to use the script

See below for notes on how to run this on a Synology NAS.

  1. Download a copy of the script from Github or create a .sh file (e.g. create-compose-files.sh) on your server with the following code:
#!/bin/sh

# Path to backup location, update if needed.
backup_dir="$HOME/compose-backups"

docker pull red5d/docker-autocompose
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
docker ps --format '{{.Names}}' > containers.txt
while IFS="" read -r p || [ -n "$p" ]
do
  docker run --rm -v /var/run/docker.sock:/var/run/docker.sock red5d/docker-autocompose $p > "$backup_dir/$p-$current_time.yaml"
done < containers.txt
find "$backup_dir" -name "*.yaml" -mtime +5 -exec rm {} \;

(up to date as of November 15th, make sure you check the repository for updated versions)

2. Make the file executable:

chmod +x create-compose-files.sh

3. Create a compose-backups folder in your home directory

mkdir ~/compose-backups

4. Run the script:

./create-compose-files.sh

5. Voila! Check your compose-backups folder:


Synology NAS gotchas

A couple of changes will need to be made for it to work on a Synology NAS.

  1. Update the backup_dir value to wherever you want the compose files to be created. I made a folder in my NAS user's home directory.
#!/bin/sh

# Path to backup location, update if needed.
backup_dir="/volume1/homes/andy/compose-backups"

docker pull red5d/docker-autocompose
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
docker ps --format '{{.Names}}' > containers.txt
while IFS="" read -r p || [ -n "$p" ]
do
  docker run --rm -v /var/run/docker.sock:/var/run/docker.sock red5d/docker-autocompose $p > "$backup_dir/$p-$current_time.yaml"
done < containers.txt
find "$backup_dir" -name "*.yaml" -mtime +5 -exec rm {} \;

2. You need to use sudo to run the script

sudo ./create-compose-files.sh


Related: Check out this post on how to run Docker commands without sudo on a Synology NAS