Skip to content

Instantly share code, notes, and snippets.

@pansapiens
Created March 11, 2025 20:22
Show Gist options
  • Save pansapiens/f8765902ef3bb522a275844640ba020b to your computer and use it in GitHub Desktop.
Save pansapiens/f8765902ef3bb522a275844640ba020b to your computer and use it in GitHub Desktop.
Convert a Apptainer/Singularity SIF file to a Docker image.
#!/bin/bash
set -euo pipefail
function show_usage() {
echo "Usage: $0 <input.sif> [docker_image_name:tag]"
echo
echo "Converts a Apptainer/Singularity SIF file to a Docker image."
echo
echo "Arguments:"
echo " input.sif Input Apptainer/Singularity image file"
echo " docker_image_name:tag Optional Docker image name and tag"
echo " (defaults to basename of input file)"
exit 1
}
# Check for required commands
for cmd in apptainer unsquashfs docker; do
if ! command -v $cmd &> /dev/null; then
echo "Error: Required command '$cmd' not found"
exit 1
fi
done
# Check arguments
if [ $# -lt 1 ] || [ $# -gt 2 ]; then
show_usage
fi
input_sif="$1"
if [ ! -f "$input_sif" ]; then
echo "Error: Input file '$input_sif' not found"
exit 1
fi
# Set docker image name
if [ $# -eq 2 ]; then
docker_image="$2"
else
docker_image="$(basename "$input_sif" .sif):latest"
fi
# Create temporary working directory
work_dir=$(mktemp -d)
trap 'rm -rf "$work_dir"' EXIT
echo "Converting '$input_sif' to Docker image '$docker_image'..."
# Find the squashfs partition ID
squashfs_id=$(apptainer sif list "$input_sif" | grep -i 'Squashfs' | awk '{print $1}')
if [ -z "$squashfs_id" ]; then
echo "Error: Could not find Squashfs partition in SIF file"
exit 1
fi
# Extract the squashfs filesystem
echo "Extracting squashfs filesystem..."
apptainer sif dump "$squashfs_id" "$input_sif" > "$work_dir/data.squash"
unsquashfs -dest "$work_dir/data" "$work_dir/data.squash"
# Create Dockerfile
cat > "$work_dir/Dockerfile" << 'EOF'
FROM scratch
COPY data /
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
CMD ["/bin/bash"]
EOF
# Build Docker image
echo "Building Docker image..."
(cd "$work_dir" && docker build --tag "$docker_image" .)
echo "Successfully created Docker image: $docker_image"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment