Shakespeare had a habit of writing a small part into each of his plays that would make audiences laugh, as a bit of comic relief from the tragedy at hand. A good example of this is the gravedigger's role in Hamlet. Others are the Fool in King Lear and Touchstone in As You Like It. Shakespeare decided to make the drunken porter scene in Macbeth comical, but it has a serious purpose.
Macbeth and his wife have planned to pretend they were sound asleep when the King's body is discovered. Lady Macbeth tells her traumatized husband
Get on your nightgown, lest occasion call us
And show us to be watchers.
However, Shakespeare wanted Macbeth to be present when Macduff discovers the body. This would be the only time that Macbeth and Macduff, the protagonist and antagonist, would appear together in the entire play until their death duel at the very end. Shakespeare invented the prolonged knocking to force Macbeth to come down in person to find out why nobody is opening the gate. He is forced to play a different part than the one he was expecting, and he does a terrible job of greeting Macduff and Lennox and of pretending to be innocent when Macduff goes into the King's chamber and comes out screaming,
O horror, horror, horror!
Before Macbeth appears on the scene, the drunken Porter has finally opened the gate--and we learn that it is Macduff who has been doing all the knocking. The Porter's drunken condition is explanation enough for his dereliction of duty. He tells Macduff that the entire household staff was drunk because they were "carousing till the second cock" (which my edition of the play explains was about 3 A.M.). All the Porter's speech is only intended to explain why there was so much knocking, and the knocking was only included in the play in order to make Macbeth come down in his nightgown.
If the Porter produces a lot of laughter, that is advantageous because it will make the audience overlook some logical questions. Why did such an important thane as Macduff have to spend the night outside the castle? Why did Macbeth and his wife permit the entire household staff to get blind drunk when they were hosting the King himself? Why didn't Duncan ask someone to wake him who would be sleeping inside the castle that night? Banquo was sleeping inside, and so were many others. Why doesn't Macduff, who has a fiery temper, beat the Porter, or at least berate him, for keeping him waiting outside in the cold and rain? But when Macduff finally enters, dripping wet, he asks the Porter
Was it so late, friend, ere you went to bed
That you do lie so late?
Macduff's gentle tone is highlighted by the fact that he calls the Porter "friend."
There are answers to all these questions, but they go beyond the scope of the scene with the drunken Porter. At any rate, the scene was not just thrown in for comic relief, and the knocking at the gate was not invented, as Thomas De Quincey suggested, for dramatic effect.