docker_layers.sh 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #!/usr/bin/env bash
  2. # This script takes a single Docker image tag (e.g. "ubuntu:latest") as input
  3. # and shows the contents of the filesystem for each layer in the image.
  4. if [ $# -ne 1 ]; then
  5. echo "Usage: $0 <image_tag>"
  6. exit 1
  7. fi
  8. IMAGE=$1
  9. # TMPDIR=$(mktemp -d)
  10. mkdir -p "$PWD/tmp"
  11. TMPDIR="$PWD/tmp"
  12. # Save the Docker image to a tar archive
  13. echo "Saving Docker image '$IMAGE'..."
  14. if ! docker save "$IMAGE" | pv > "${TMPDIR}/image.tar"; then
  15. echo "Failed to save image '$IMAGE'. Make sure the image exists and Docker is running."
  16. rm -rf "${TMPDIR}"
  17. exit 1
  18. fi
  19. cd "${TMPDIR}" || exit 1
  20. # Extract the top-level metadata of the image tar
  21. echo "Extracting image metadata..."
  22. pwd
  23. tar -xzf image.tar
  24. chmod -R 777 .
  25. cd blobs/sha256 || exit 1
  26. # Typically, the saved image will contain multiple directories each representing a layer.
  27. # Each layer directory should have a 'layer.tar' file that contains the filesystem for that layer.
  28. for LAYERFILE in ./*; do
  29. if [ -f "${LAYERFILE}" ]; then
  30. mv "${LAYERFILE}" "${LAYERFILE}.tar"
  31. mkdir -p "${LAYERFILE}"
  32. tar -xzf "${LAYERFILE}.tar" -C "${LAYERFILE}"
  33. rm "${LAYERFILE}.tar"
  34. echo "-----------------------------------------------------------------"
  35. echo "Contents of layer: ${LAYERFILE%/}"
  36. echo "-----------------------------------------------------------------"
  37. # List the files in the layer.tar without extracting
  38. tree -L 2 "${LAYERFILE}"
  39. echo
  40. fi
  41. done