Golf courses didn’t always have 18 holes. The number of holes used to vary widely: 11, 22, 24, etc. As with most golf tradition-related questions, the reason why 18 became the standard goes back to St. Andrews of Scotland, the granddaddy of all golf courses.
The original course at St. Andrews (dating back to the 15th century!) consisted of 11 holes along a narrow strip of land next to the sea. Each hole was played twice, for a total of 22. In 1764, two of the holes were judged to be too short, so the course made the switch from 22 to 18 holes (nine holes played two times each).
In 1858, the Royal & Ancient Golf Club of St. Andrews, not an institution to be trifled with, issued an official decree that one round of links, or 18 holes, constituted an official match. Other courses pretty much followed suit, and by the 1870s, 18 holes was the standard.
One legend claims that the number 18 originated as a suggestion from one of the St. Andrews old-timers, who noted that it took exactly 18 shots to finish a fifth of scotch — a shot per hole. However, this is just a rumor, so you can leave your hip flasks at home.