When a virus enters your body, your body has to recognize it, then produce a protein called an antibody. These antibodies attach to the virus and neutralize it; however, in the time it takes your body to produce enough antibodies, the virus may have already multiplied enough to make you sick.
How Do Vaccines Work?
Here's the good news once your body has learned to make the right antibodies, it can make them much faster, neutralizing the virus before you get sick.
Vaccines teach your body to recognize and react to a virus quickly.
There are two types of vaccines you can get to teach your body to recognize a virus. Inactivated vaccines contain a dead virus, which cannot infect your cells, but your body recognizes it as a virus and produces antibodies to neutralize it. The vaccines for polio and the seasonal flu use dead viruses.
The second type of vaccine contains an attenuated virus. This virus is alive, but has been grown in the lab for several generations, so it isn't able to multiply very well in humans. With the attenuated virus multiplying very slowly, your body is able to produce the correct antibodies before you get sick. Measles and mumps vaccines are both made with attenuated viruses.
So, How Does All This Work?
When most people in a community have become resistant to the virus, either through a vaccination or by having the virus and recovering, the community develops what is called "herd immunity".
The nice thing about herd immunity is that it becomes statistically less likely for the germ to find a person without immunity. This protects members of the community who haven't been vaccinated, or had the disease, by reducing their chances of encountering an infected person.