Authors get around 10% of the cover price of a book as royalties, it depends on several factors. The rest goes to the publisher. So some do lose money, but the break even for the publisher is usually well before the advance is fully covered by royalties.

Well the publisher also pays for the book to be bound, edited, overhead for their staff, cover art. Many books don't sell for the full retail price and are discounted. So net of all of this a 10% profit margin is common, they aren't keeping 90% of the book sales.

Long story short - publishing houses are venture capital firms.

Most of their investments fail miserably, but they only need one Google/Stephen King.