He may have a impacted anal gland. Dogs have glands on either side of the rectum which can become impacted and infected. Some dogs need these glands expressed to prevent infected or to help clear up infection.
The procedure isn't that difficult and many people choose to do it at home to save on vet charges. The best thing to do though is to do it in the bathroom because frankly the smell is quite nasty. Its as simple as gently squeezing the gland to express it. I would suggest having him examined by the vet this time to have the glands expressed if this is the issue and to begin treatment for infection if it has gone that far. In the future you can express them at home if it happens again. (You may want to watch the vet express this time so you know how to do it as well).
Here is a link that we give our clients when they want to do it at home. It has a step by step guide as well as pictures. You may want to keep a eye on the glands in the future and do the express at home if there is a issue.