Typical new car dealerships make around $1,000 in profit on each vehicle sold. On used cars, they will generally make around $3,000. However, the real bread and butter is the service department. Finance department is generally second.
When you buy a new car, you are more likely to bring it back to the dealership than to go to an independent mechanic. Especially when the brand makes it difficult if not almost impossible for others to work on their new vehicles. This wasn't as easy years ago but with the amount of electronics and computers in modern vehicles it's a lot more about having the very specific tools and software, not just mechanical knowledge. Dealerships can make sure they have first, or exclusive, access to certain parts and even tools. Plus, they can usually be more efficient by specializing in a limited number of vehicles which means they might quote you the same time as an independent mechanic, but will do the work faster.
Dealerships can afford to sell cars at or below cost because they know they'll probably make it up on the back end with the service. And if they're lucky, a few years down the road that same buyer will trade their vehicle in and start the cycle all over again. Except now the dealership gets to make a nice profit on a used vehicle - potentially one they can certify and charge even more for.