Same reason soldiers are willing to sacrifice their own lives for the group.
Evolution isn't about your own genes surviving to the next generation. It's about your individual genes competing amongst themselves to survive to the next generation. Your genes aren't just present in your own body; they're also present in other people and even other species. And it doesn't matter to those genes whether they survive through your body, other peoples' bodies, or other species' bodies.
Imagine gene A is present in individuals X, Y, and Z. If gene A suicides a copy of itself in person X and that causes Y and Z to have kids with gene A, gene A will kill person X. Thus, the soldier.
This also works across species. There are some organisms that give themselves up to parasites that eat their bodies or hijack their brains. The host being eaten alive is the 'soldier' in that case. Both of these organisms will have common genes that are destroying the host to make more copies of themselves. In both cases, this is a symbiotic-parasitic relationship for the benefit of a mutual gene.
Thus, religion, homosexuality, and so many other things that don't make sense for spreading your genes at the individual level. EG -- gay men like dudes, a lot. Sisters of gay men with those same man attraction causing genes really, really, really like dudes. And they have more kids than sisters of straight men. So the gay gene sacrifices itself in the gay person's genome to more than make up for it with success in his family member's genomes. Etc.