The primary purpose of a firewall is to act as a security barrier that monitors and controls incoming and outgoing network traffic. It enforces security rules to block unauthorized connections and prevent malicious traffic from entering or leaving a network or individual computer, particularly via external networks like the internet.