How can I prevent it?

Your best bet is to wash your penis thoroughly every day, especially if you are uncircumcised.