Skip to content

Instantly share code, notes, and snippets.

@mogoh
Created April 7, 2025 15:33
Show Gist options
  • Select an option

  • Save mogoh/ea9f3256683cd42afc69fea6f74c30a8 to your computer and use it in GitHub Desktop.

Select an option

Save mogoh/ea9f3256683cd42afc69fea6f74c30a8 to your computer and use it in GitHub Desktop.
Simple Bash Script Template to Run a Script inside a Docker Container Once
#!/usr/bin/env bash
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
if [[ "${1-}" =~ ^-*h(elp)?$ ]]; then
echo 'Usage: ./one-time-docker
This script is a template to
- one time run a docker container,
- execute a script inside,
- save some output to ./output, and
- delete the container afterwards.
Adjust as needed.
Use:
export TRACE=1
for better debugging.
'
exit
fi
# Set variables
IMAGE="docker.io/library/debian:stable-slim"
HOST_OUTPUT_DIR="./output"
ARTIFACT_PATH="/output/artifact.txt"
USER_ID=$(id -u)
GROUP_ID=$(id -g)
# Make sure output directory exists
mkdir --parents "${HOST_OUTPUT_DIR}"
# Create a temporary file to hold the container script
SCRIPT_FILE=$(mktemp)
# YOUR SCRIPT HERE ###########################################################
cat <<EOF > "${SCRIPT_FILE}"
mkdir --parents /output
echo 'Hello from inside the container!' > ${ARTIFACT_PATH}
EOF
##############################################################################
# Run the container, generate the artifact, and copy it out
docker container run \
--rm \
--user "${USER_ID}:${GROUP_ID}" \
--mount type=bind,source="${HOST_OUTPUT_DIR}",target=/output \
--mount type=bind,source="${SCRIPT_FILE}",target=/container_script.sh,readonly \
"${IMAGE}" \
bash /container_script.sh
# Clean up the temporary script file
rm --force "${SCRIPT_FILE}"
echo "Artifact extracted to: ${HOST_OUTPUT_DIR}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment