As in soda, the dissolved carbon dioxide is released when the liquid is poured, less if the pour is gentle, more if the more if the pour is rougher. Unlike soda, beer has protein in it, which helps to retain the foam. BTW, greasy glasses reduce the "head".
Update: The other day, I scrambled some eggs in a bowl, then sprayed water into the bowl to keep the egg from drying there. The foam lasted for hours because of the protein in the albumin. You can buy overpriced albumin to add to your cocktails if you want them with foam on top. It might work with your beer, too.