Skip to content

Instantly share code, notes, and snippets.

@jneuendorf-i4h
Forked from Gems/docker-compose.sh
Last active October 20, 2023 07:46
Show Gist options
  • Save jneuendorf-i4h/6bf01a1c151c53a5a3ce7930dd4abef4 to your computer and use it in GitHub Desktop.
Save jneuendorf-i4h/6bf01a1c151c53a5a3ce7930dd4abef4 to your computer and use it in GitHub Desktop.
A `docker-compose` wrapper for multiple configuration files with relative paths
#!/usr/bin/env bash
# A `docker-compose` wrapper for multiple configuration files with relative paths.
# Specifically, build contexts are relative to each compose file's location.
#
# > The way multiple compose file get merged together is now defined by the Compose Specification:
# > https://github.com/compose-spec/compose-spec/blob/master/spec.md#compose-file
# >> Relative paths MUST be resolved based on the first Compose file's parent folder,
# >> whenever complimentary files being merged are hosted in other folders.
# See issue https://github.com/docker/compose/issues/3874#issuecomment-1012923100
PROJECT_NAME=$(basename `pwd`)
# Create temp file securely
TMP_FILE=`mktemp /tmp/docker-compose.XXXXXX` || exit 1
mv ${TMP_FILE} ${TMP_FILE}.yml
TMP_FILE=${TMP_FILE}.yml
# Clean up
finish() {
rm ${TMP_FILE} ${TMP_FILE}.tmp 2>/dev/null
}
trap finish EXIT
# Prepend given file to config in order to keep the file's relative context
compose-config() {
mv -f ${TMP_FILE} ${TMP_FILE}.tmp
# Add the file twice: 1st for the context, 2nd for config overrides
docker compose -p ${PROJECT_NAME} -f ${1} -f ${TMP_FILE}.tmp -f ${1} config > ${TMP_FILE}
rm -f ${TMP_FILE}.tmp 2>/dev/null
}
# Separate -f/--file arguments from the rest
args=()
files=()
while [ -n "$1" ]; do
case "$1" in
-f | --file)
shift; files+=($1)
;;
*)
args+=($1)
;;
esac
shift
done
# Generate config
for f in ${files[@]}; do
compose-config ${f}
done
# Prepend version
mv -f ${TMP_FILE} ${TMP_FILE}.tmp
echo 'version: "3"' > ${TMP_FILE}
cat ${TMP_FILE}.tmp >> ${TMP_FILE}
rm -f ${TMP_FILE}.tmp 2>/dev/null
echo -e "
FINAL CONFIG
------------
"
docker compose -f ${TMP_FILE} config
docker compose -f ${TMP_FILE} ${args[@]}
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment