Summarize this article:

Instead of inserting your earbuds so the cord hangs straight down from your ear canal, insert them "upside down" and loop the cord over the back of your ear. This may feel strange at first if you're not used to it, but it will prevent the buds from slipping out every time the cord is slightly jerked or pulled. Earbuds are meant to fit snugly into your ear canal. If your earbuds don't seem to sit comfortably in your ears, you may simply need to insert them more carefully. Stretch your earlobe gently with one hand to open the ear canal while inserting each earbud, then release so that your ear cavity shapes itself around the earbud and forms a tight seal. Don't disregard those extra foam or silicone tips that come packaged with your earbuds. Experiment with different sizes to see which is most comfortable for you. It's even possible that one of your ears is slightly larger than the other, and you may want to use two different sizes. You can purchase accessories for your existing earbuds to customize the fit. These are great for improving the fit of those cheap round earbuds that came free with your device. A popular choice is Yurbuds, soft rubber attachments that create a more snug fit into the ear. They can even be made in custom sizes. A buildup of earwax can cause your earbuds to fit poorly and fall out. Using cotton swabs to remove earwax can actually cause the wax to be pushed against your eardrum, causing a blockage and possibly resulting in discomfort while wearing earbuds. Don't use Q-tips, and see a doctor if you think you may have an earwax blockage.

Summary:
Hang the cord over your ears. Insert the buds firmly into your ears. Use the attachments that come with your earbuds. Purchase special attachments. Don't clean your ears with cotton swabs.