Besides the common burning excess natural gas others point out, they also serve a more general safety purpose.
Many if not most of the processes in a refinery or chemical plant deal with gases as inputs, intermediate or final products. Just like with natural gas (as everyone else mentioned) if those products are released it is much safer to combust them than to allow them to be released in their uncombusted form. So, many of the flares you see are kind of like pilot lights on your water heater or other natural gas appliances. They stay lit so that when there is an upset in the plant the products can be shunted to the flare stack and burned (automatically) before they are released.
If you have to ask yourself if you have ever seen a plant burning off excess product during a process upset, you haven’t. If the plant or process is big enough, the roar can be heard for miles and they can light up the night as bright as day for just as far.