By a slow, life-long process: When we are born we have had no exposure to bugs in the outside world; that is why it is so important to have everyone vaccinated against diseases to protect babies who have very weak immune systems. As we grow up, we experience more and more bugs, viruses and other challenges and our immune system learns and adapts with this. That is why we give vaccines in childhood because the immune system is learning, and can protect us for life from some diseases.
The cells of the immune system that do this learning are the lymphocytes. As we mentioned above, lymphocytes recognise other cells by interrogating proteins on the surface of cells. Other cells in our immune system (such as dendritic cells mentioned above) can teach lymphocytes who is friend and who is foe, by holding up pieces of these proteins for them to examine.
Lymphocytes can then remember these identifications for our whole life, protecting us from infections and understanding who is friend and who is foe. This is why vaccines work. A vaccine is usually a weakened or dead form of a virus that won’t make you sick, but will teach your immune system how to recognise and fight that infection. If you are later infected by that particular virus, your immune system already knows how to fight it and will kill the virus before it can make you sick.
This is also how lymphocytes can recognise cancer cells, or normal human cells infected with viruses. While these abnormal cells look mostly like a normal human cell, the virus or the changes to proteins caused in cancer can make tiny changes to the proteins on the surface of the cell. The immune system is so sensitive that it can detect these tiny changes and therefore can recognise cells that are infected or cancerous.