I found this today while searching the web exactly for how to do that, but the answer wasn't very easy to find.
https://hibern8.wordpress.com/2018/09/25/drupal-8-bootstrap-from-external-script/
Reproducing here in case the site goes offline.
As this code is from 2018, it should work with Drupal 8, maybe Drupal 8.9, and hopefully with Drupal 9 and 10. I will test when I have time.
Bootstrap Drupal 8 from external script