His brain sends a message to his ears, which lock him to the top of the doghouse.
Charles Schulz seems to have addressed this question only once, in the 25th anniversary book "The Peanuts Jubilee". I haven't found this anywhere online (including the Peanuts Wikia) so I thought I'd upload it and share it here.
The more Snoopy moved into his life of fantasy, the more important it became for his doghouse to remain in side view. You simply cannot have a dog doing and thinking the things that Snoopy does on a realistic doghouse. The image is much more acceptable when the doghouse is drawn only from the side. When necessary, it almost loses its identity completely. Snoopy's typewriter could never balance on the peak the way it does and, of course, Snoopy himself is somewhat of a mystery when one examines his sleeping pose closely. I once inquired of a veterinarian how birds stay on tree limbs when they fall asleep. He told me that their claws receive a message from their brain after they have fallen asleep, which tightens a certain muscle, keeping them from tumbling off the branch. He said a similar thing occurs to horses, allowing them to sleep while standing. Humans do not have this ability. When I am asked how Snoopy remains on top of his doghouse after falling asleep, I am now able to say that his brain sends a message to his ears, which lock him to the top of his doghouse.
Sources here and here
A commenter on Reddit pointed out that Charles Schulz references this in the April 29, 1963 strip: