This idiom originated in the early days of pubs and taverns. In those days, it was common for the owner of the establishment to offer free drinks or meals to certain patrons, especially regulars or those who were particularly generous.
The phrase "on the house" is believed to have come from the fact that the owner would often write these free items on a chalk board or ledger that was kept near the house or main entrance of the tavern.
Over time, the phrase became associated with anything that was free or offered without charge, and eventually spread to other businesses and situations.