Glowing may be a side-effect of a very different original purpose
I used to think there was a small molecule called luciferin that emitted the light of bioluminescence. I was not exactly wrong, but there is not just one luciferin. There are many, and to look at their molecular structures you’d be justified in concluding they have nothing in common with one another.
The best known is firefly luciferin, a dimer of two thiazol derivatives: that is, of two five-membered heterocyclic rings containing sulfur and nitrogen. Then there’s bacterial luciferin, which is a derivative of vitamin B2 (riboflavin). Some fungi glow because they contain a derivative of hispidin, a conjugated molecule based on pyrone. Some single-celled marine organisms called dinoflagellates harbour an impressive luciferin related to chlorophyll, in which the porphyrin ring has been opened up at one point.
As this diversity of luciferins testifies, bioluminescence is not a trick learnt long ago in evolutionary history and then passed on throughout the tree of life. It arose independently many times (perhaps more than 50), a fact evident also in the enzymes that react with luciferins to cause light emission. Called luciferases, these proteins are very different in their structures: the genes encoding them are not closely related analogues of one another, but seem to have independent origins. Some bioluminescent systems also involve accessory proteins that modify the emission wavelength of the luciferin.