The knocking at the gate has been going on for a long time in Act 2, Sc. 2. It is still going on when the Porter appears at the beginning of Sc.3. One purpose of this scene is to explain why it took so long for anyone to open the gate. According to the Porter, "...we were carousing till the second cock." Everybody was drunk, and the Porter is still drunk. But the main purpose is to justify all the loud knocking which Macduff is forced to do. This knocking will bring Macbeth down in his nightgown to find out what is going on. Shakespeare wanted Macduff to discover King Duncan's body and wanted Macbeth to be present when he did. But Macbeth and his wife had both planned to pretend to have been sound asleep all night.
Previously, Banquo tells Macbeth that:
The King's abed.
He hath been in unusual pleasure, and
Sent forth great largess to your offices.
(Act 2, Sc. 1)
The servants are all drunk because the King's largess included a lot of liquor.
Many critics take the Porter scene as pure comic relief. But it has a much more serious purpose. Shakespeare wanted Macduff to discover the body, but he wanted Macbeth to be there when he did. So he had to invent the knocking (and the reason for it) in order to force Macbeth to come out of his bed chamber. Shakespeare also had to explain why Macduff hadn't been accommodated inside the castle, instead of having to sleep outside in a hovel. So in the same conversation with Banquo in Act 2, Sc.1, he has Macbeth say:
Our will became the servant to defect,
Which else should free have wrought.
So in just a few lines Banquo tells the audience why the servants are all drunk and Macbeth tells the audience that he couldn't accommodate Macduff and other dignitaries because he wasn't prepared for such an influx of people.
I refer you to Thomas De Quincey's "On the Knocking at the Gate in Macbeth," which is covered in eNotes. It focuses strictly on the knocking but does not explain the reason for the knocking.