Imagine this: we are all born with a functional immune system which is pre-programmed with knowledge of what bacteria, viruses, and many parasites look like, so it can immediately deal with these without prior exposure. This is the innate immune system, and in many organisms is the only immune system.
On top of that, a database is created which consists of fragments of all our bodies' molecules. This database is used to train the adaptive immune system. The thymus will then present these molecules to new white (T) cells, and screen out the ones that recognize these "self" molecules. This is the adaptive immune system.
Still on top of that, there's another tier, because maybe 0.1% of T cells escape the first-pass screening. You now have a series of checks and balances which screen for these escaped cells outside the thymus, and either reduce their functioning or eliminate them entirely. This is peripheral tolerance (what the Nobel prize in medicine was awarded for this year).
And when there's an actual infection, this system is able to spin up a few VMs, run a large bug-search model, and create a pool of tailor-made antibodies and T cells specific to the new bug, which in most cases are enough to deal with the infection.
So when all is said and done, and the system is trained and working as expected, you now have an immune platform which, on top of recognizing all its own molecules, can also recognize pathogens, including differentiating disease-causing ones from the benign ones; can also deal calmly with the enormous diversity of things we put in our mouths, noses, and other orifices; and in most cases doesn't actually go rogue.
But sometimes, it can be overcome by peanuts.