The margins on generic drugs are razor thin. Most of the recent drug shortages are due to a lack of starting materials or manufacturing problems. Both of these can be traced back to the fact that there is very little money to be made in generic drugs. They are basically commodities.
Other sources of shortages are due to the fact that the government issues drug companies production quotas for some drugs, which the drug companies aren't allowed to go over even if their competition has problems. My understanding of how this works is that the DEA tells companies A, B, and C that they can each make 20 units of Drug X. Then the FDA tells company C that their Drug X isn't up to snuff and they can't make any more this year. The 40 units that companies A and B make isn't enough to cover demand, but they can't increase their production to 30 units because the DEA has already filed their paperwork.