Most critics think the porter was introduced to provide comic relief, but Shakespeare had a more practical purpose. Macbeth and his wife had planned to pretend to be sound asleep in their chamber when Duncan's body was discovered. The prolonged knocking forces Macbeth to come out and be present when Macduff (who is doing all the knocking) discovers the King's body. This is more effective dramatically, and this is the only time that Macduff and Macbeth will be seen together before their death duel at the end. The porter has to be drunk to explain why Macduff had to do so much knocking. Macduff will ring the alarm bell and call everybody to the scene of the crime, while Macbeth has to suffer agonies of guilt and anxiety while pretending to be outraged and astounded by the murder he himself committed.
Thomas De Quincey wrote a famous essay titled "On the Knocking at the Gate in Macbeth." He seemed to think the knocking was mainly intended for the emotional effect produced by all the noise. He was wrong.