When germs such as bacteria or viruses invade the body, they attack and multiply. This invasion is called an infection, and the infection is what causes illness. The immune system uses several tools to fight infections, such as:
Macrophages, which are white blood cells that swallow up and digest germs whether dead or dying cells; leaving behind parts of the invading germs called antigens. The body identifies antigens as dangerous, and stimulates the body to attack them.
Antibodies attack the antigens left behind by the macrophages. These are produced by defensive white blood cells called B-lymphocytes
T-lymphocytes are another type of defensive white blood cell. They attack cells in the body that have already been infected.
The first time the body encounters a germ, it can take several days to make, and use all the germ-fighting tools needed to get over the infection. After the infection, the immune system remembers what it learned about how to protect the body against that disease.
How Then Do Vaccines Work?
Vaccines help develop immunity by imitating an infection. This type of imitation infection, however, does not cause illness, but causes the immune system to produce T-lymphocytes (also called memory cells, because they are primed to remember past infections and go into action quickly when similar cases arise) and antibodies.
Sometimes, after getting a vaccine, the imitation infection can cause minor symptoms, such as fever. Such minor symptoms are normal and should be expected as the body builds immunity. Once the imitation infection goes away, the body is left with a supply of T-lymphocytes, as well as B-lymphocytes that will remember how to fight that disease in the future.
However, it typically takes a few weeks for the body to produce T-lymphocytes and B-lymphocytes after vaccination. Therefore, it is possible that a person who was infected with a disease just before or just after vaccination could develop symptoms and get a disease, because the vaccine has not had enough time to provide protection.

Many of these vaccines work by carrying a weaker or dead version of the germ, just enough to signal to our body to go on the attack, but not so much that an infection flares up, these are called live, attenuated vaccines.

Inactivated vaccines fight viruses, and are made by inactivating, or killing, the virus during the process of making the vaccine. An example is the Polio vaccine
Toxoid vaccines prevent diseases caused by bacteria that produce toxins (poisons) in the body. In the process of making these vaccines, the toxins are weakened so they cannot cause illness. Weakened toxins are called toxoids
Subunit vaccines include only parts of the virus or bacteria, or subunits, instead of the entire germ.

 Many vaccines provide lifelong protection and though none is 100% effective, the more people in a population that get vaccinated the more diseases are kept under control diseases.