What you describe is a perianal haematoma, or external pile. Despite this name, it is not actually a pile at all, but is really like a blood blister such as you get on your thumb if you trap it or hit it with a hammer.
What causes a blood blister in this situation is that when the bowels are opened the anus stretches, and sometimes a tiny blood vessel will rupture and cause a leak of blood just under the skin. It raises a pea-sized swelling right on the margin of the opening of the anus. It is very tender at first, because the skin is stretched over it in this very sensitive region, and when it is further stretched by passing a stool, it is even worse.
Most of these haematomas do not need any treatment.