The valence orbital of atoms have sub-orbitals (s, p, d, and f ). there is 's' suborbital which can hold 2 electrons. There are 'p' sub-orbitals which can hold a total of 6 electrons. Since an atom is stable when all of the electrons are paired and 2+6 = 8, an atom must have 8 electrons in its valence shell to pair all of the electrons.
The octet rule does not apply to all atoms though, for He, it has only 2 electrons and it is stable because it's valence shell is paired. for transition metals there is a d suborbital which can hold 10 electrons, meaning that now an atom may have 18 electrons in its valence shell. So it follows 18 electron rule.
Regards