They occur when certain areas of the brain are activated. Nocturnal penile erections occur during Rapid Eye Movement (REM) sleep (the phase during which we dream). This explains why people with spinal cord damage can still get erections and why you can get erections when not sexually aroused.
This same mechanism can occur without the involvement of the brain, in an uncontrolled reflex action that is in the spinal cord. Several hormones are involved in influencing the brain’s response, such as testosterone (the main male hormone).