The ancestral canine/wolves had the ability to express anal glands naturally, to mark their territory, deter any danger or other animals...keeping their young safe from harm, etc.
The domesticated dog has lost the ability to express naturally this way (thank goodness loll!). It can happen when they are frightened or if the glands are full. Like Breny mentioned, they do express some naturally while going # 2, so a diet consisting of fiber (green beans &/or kibble w/4-5% fiber) will help bulk/firm things up to help it along. It can also mean it's impacted, so a trip to the vet or groomer is in order...my vet taught me how to express @ home.
When they do express, a butt wash is the only option to get rid of the smell.