This is how a Lufthansa co-pilot explains it: Modern commercial aircrafts are built in such a way that two pilots are needed to steer them. Therefore, since only two pilots are on board on most of the flights, the pilots are now allowed to sleep.
On very long flights, with flight times of around eight hours or more, a third pilot supports the crew. In this case, each of the pilots can take turns to have a break during the cruise flight. There is a special, very small room on board, called the cockpit crew rest, for these breaks. It is located close to the cockpit and has a resting bunk. There is often a similar resting area in a different place in the aircraft for the cabin crew.
Incidentally: The pilots often enter the rotation times of the breaks into the air data computer. In this way, one not only knows when one can sleep, one can even see “where” one is sleeping on the display: “Today, I am going to sleep from Iceland to Canada.”