Nightcaps—knitted wool or silk stocking caps– were worn from the fourteenth to the nineteenth century, until the arrival of central heating. Before the fourteenth century, people probably slept naked, according to Elizabeth Ewing in Dress and Undress: A History of Women’s Underwear—and they all slept together, for warmth. Which must have been awkward when one had house guests.
In the seventeenth century, wigs for men became wildly popular in most of Europe. Most men shaved their natural hair, so wearing a cap at night would have helped keep the head warm. Fires went out at night, even in homes with lots of servants, so bedrooms could be very, very cold. The rest of your body could stay covered under the blankets, but your head was exposed to the chill. Think how unpleasant it would have been to step out of bed to use your chamber pot. A nightcap would make a lot of sense.