It's a surprisingly tricky problem, btw, at least for some languages. Here's a nice 2014 talk by Jessica McKellar: Building and breaking a Python sandbox that gives insight into some pitfalls. Might be "solved" by now though, don't know.
Running stand alone and throw away code in a container, is very different from running a user provided script within your long lived application securely.
Think credentials, Db access, file system access, network
But you want to access the DB and write to files and the network just not anywhere, so you have different process and communicate via rpc
https://www.youtube.com/watch?v=sL_syMmRkoU