If your MacBook goes to sleep when you close the lid, check your power settings:
Go to System Settings > Battery > Options and enable “Prevent automatic sleeping on power adapter when the display is turned off”3.
In System Settings > Lock Screen, set “Turn display off on power adapter when inactive” to Never34.
On newer MacBook models (Apple Silicon, 2021+), clamshell mode should activate automatically when you close the lid with an external display and power connected.