How to run untrusted source code inside of a container

There are many websites that allow you program online. Can docker be used to run potentially ‘unsafe’ code by a user and if so what would be the best way to do this?

I’m referring to these websites that let you enter javascript, ruby, python code in an online editor and then when the user presses the Run button it will compile the code and return the response or the compilation error message.

Would you suggest running a very short lived docker instance that compiles the code, returns the output and then shutsdown?

What security measures would need to be considered to make this safe?