One word: "chainline"
A chain cannot move off of a gear unless a sideways force is acting upon it. The
deraileur usually does that job and also keeps the chain aligned with the cog on
the freewheel. if the chain is not properly aligned, or if the rear wheel is
skewed to one side, a sideways force will be applied to the chain and cause it
to move off of the intended freewheel cog.
To get the proper chainline, your chainring need to be horizontally aligned with
the one of the cogs on your freewheel, or as close to it as possible.
Typically, that is the cog in the middle of the freewheel. In the case where
you have an even number of freewheel cogs, pick one of the ones closest to the
middle.
You will have to adjust your crankset, or rather, the bottom bracket, so that
you are in alignment with the middle freewheel cog. Take a straight edge, or a
laser guide to help you find the right point.
Once you've established a proper chainline, you should be OK, but if you're
still having problems, look at whether the wheel is sitting square between the
stays,and/or if your frame is bent.
Jim