Men will often wake up in the morning to find that their penis has filled with blood during the night, and is erect. The scientific name for this is Nocturnal Penile Tumescence. While this is very common and not related to any medical issues, it is often embarrassing and uncomfortable, especially if you share your bed with a partner. A man's penis will often become erect during the night when he dreams of something that arouses him. Urine retention, which occurs when the bladder is full and begins filling the urethra with urine, can again stimulate the penis enough to cause an erection. However, there are ways to reduce the effects and regularity of morning erections.
Decide at what time of the night you are going to bed. If you plan to go to sleep at 11pm, for example, then it is a good idea to stop your intake of fluids at least two hours before you go to bed. This will give plenty of time for your body to process any liquids that you have already consumed, so you can urinate before heading upstairs.
Visit the bathroom. Expel all of the urine from your bladder, which will reduce the likelihood of excess urine making its way into your urethra during the course of the night.
Engage in sexual activity with your partner if she is willing, or masturbate. The process of ejaculating the semen from your testicles will result in a natural release of testosterone, and should reduce the likelihood of you becoming sexually aroused during sleep. This will make the subsequent morning erection much less frequent.
Lie in your bed in a comfortable position, which does not bring stimulation to your penis. Keep a distance away from your partner if not sleeping alone, and lie on your side. Lying on your side reduces the likelihood of your penis becoming aroused by the friction from your mattress underneath you, and duvet on top of you.
Go for a short walk in the morning after you wake up. This will shake off the effects of any friction which has occurred during the night between your body and the body of your partner, or the bed.
Visit the bathroom again. Relieve yourself by expelling any excess urine which may have entered the urethra as well as your bladder, and caused some arousal.
Waking up with an erection is completely normal, and is not something to worry about. While it may be embarrassing or uncomfortable, especially if you are sharing your bed with another person, it is not something which you need to seek medical treatment for -- unless you are regularly waking up in pain because of morning erections.