run-java-in-container.sh 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env bash
  2. set -Eeuo pipefail
  3. testDir="$(readlink -f "$(dirname "$BASH_SOURCE")")"
  4. runDir="$(dirname "$(readlink -f "$BASH_SOURCE")")"
  5. image="$1"
  6. # do a little extra work to try and find a suitable JDK image (when "xyzjava:1.2.3-jre" first builds, "xyzjava:1.2.3-jdk" isn't published yet :D)
  7. tryJdks=(
  8. # ideally, we'd just swap the current JRE image to JDK, but that might not exist yet (see above)
  9. "${image/jre/jdk}"
  10. # try progressively less specific versions to try and find something that can compile an appropriate ".class" object for use in $image (working our way out from "Java 8" because that's going to be the most compatible)
  11. "${image%%:*}:8-jdk-slim"
  12. "${image%%:*}:8-jdk"
  13. "${image%%:*}:jdk-slim"
  14. "${image%%:*}:jdk"
  15. "${image%%:*}:latest"
  16. 'openjdk:8-jdk-slim'
  17. )
  18. jdk=
  19. for potentialJdk in "${tryJdks[@]}"; do
  20. if docker image inspect "$potentialJdk" &> /dev/null; then
  21. jdk="$potentialJdk"
  22. break
  23. fi
  24. if docker pull --quiet "$potentialJdk" &> /dev/null; then
  25. jdk="$potentialJdk"
  26. break
  27. fi
  28. done
  29. if [ -z "$jdk" ]; then
  30. echo >&2 "error: failed to find a suitable JDK image for '$image'!"
  31. exit 1
  32. fi
  33. if [ "$jdk" != "${tryJdks[0]}" ]; then
  34. echo >&2 "warning: using '$jdk' instead of '${tryJdks[0]}' (results may vary!)"
  35. fi
  36. newImage="$("$runDir/image-name.sh" librarytest/java-hello-world "$image")"
  37. "$runDir/docker-build.sh" "$testDir" "$newImage" <<EOD
  38. FROM $jdk AS jdk
  39. WORKDIR /container
  40. COPY dir/container.java ./
  41. # if possible, use "--release" in case $jdk and $image have mismatching Java versions
  42. RUN if javac --help 2>&1 | grep -q -- '--release'; then javac --release 8 ./container.java; else javac ./container.java; fi
  43. FROM $image
  44. COPY --from=jdk /container /container
  45. WORKDIR /container
  46. EOD
  47. docker run --rm "$newImage" java -cp . container