There is a gland at the base of the penis called the bulbous gland. This is a normal part of the anatomy.
This can be a very serious problem if it is left untreated.
This usually happens because the bulbous glands of the penis have managed to engorge outside of the prepuce (outer skin), which makes it difficult, or impossible, for the penis to retract. This can lead to problems if the situation isn't corrected. Often, the vet will have to anesthetize the dog, lubricate the penis and sheath well and then use traction sutures to move the prepuce back up and over the penis. Sometimes it is even necessary to surgically widen the preputial opening. They try to avoid doing this, if at all possible, though. If the opening is too wide, the tip of the penis may stay extended and this appears to be pretty irritating to it.
If it has not retracted by the morning, you need to see the vet.
If you feel comfortable with it, you can try lubricating the penis with some ky and pulling the prepuce back over the penis. Most people don't want to get this up close and personal with their dog.
Let me know if you still have questions.