The octet rule states that atoms are most stable when their outer electron shells contain 8 electrons. Atoms attain this stable electron configuration by gaining, losing, or sharing electrons with other atoms so that their outer shells match the noble gas configuration. The rule applies mainly to nonmetals like carbon, nitrogen, oxygen, and halogens, and also some metals such as sodium and magnesium.