How does the immune system work?

How does the immune system work?

How does our body know what to do to fight viruses and bacteria? What helps the immune system recognize new pathogens? And how does it distinguish between potentially dangerous invaders and harmless microbes?