For many diseases, if you catch them once, you will never catch them again. Measles is a good example, as is chicken pox.
When these diseases make it into your body, they start reproducing. As this happens, the immune system gears up to eliminate the disease. In your body you already have B cells that recognize a virus and produce antibodies for it. But there are only a few B cells for each antibody. Once these few B cells recognize a particular disease, the B cells turn into plasma cells. They clone themselves and start pumping out antibodies. This takes time, but the disease runs it course. Eventually, the disease is eliminated.
While it is being eliminated, however, more B cells that recognize the disease clone themselves but do not generate antibodies. This set of B cells can remain in your body for years. Therefore, if the disease reappears, your body is able to get rid of it before it can do anything to you.
This is how vaccines work. A vaccine is a weakened form of a disease (either a killed form of the disease, or a similar but less virulent strain). Once the vaccine is inside your body your immune system mounts its defense, but because the disease is different or weaker the body shows no symptoms of the disease. When the real disease invades your body, the immune system is able to eliminate it immediately. Vaccines have been made to combat all sorts of diseases, both viral and bacterial.