Modern hearing aids mostly avoid feedback by having a cancelling algorithm built in to the software - they are very effective these days and you would barely ever hear a squeak. But also, there's a type of hearing aid called receiver-in-canal/ear (RIC or RIE) which has the sound output in your canal and the microphone in a small unit behind your ear and because they are far enough apart feedback does not occur. I'm wearing GN ReSound Linx 3D RICs at the moment, they are amazing tech, I can remote programme them from my iPad and stream phone calls + music directly through my hearing aids.
As someone said in another comment it is friction holding them in, a moulded aid in the canal does fit snuggly, which is what I have, but for less severe hearing losses many people wear a round one-size-fits-all flexible rubber tip in the ear, it does press against the canal enough to hold it in place but is super comfortable.
I've never once had a hearing aid pop out of my ear and I've worn them doing all sorts of sports activities.
More or less the same way headphones do.