Bacterial infections activate our Immune system, and approximately two weeks after the start of an infection, antibodies are produced. These are proteins in our blood that help white blood cells to recognize the infectious organisms and to destroy them. This ability, to specifically recognize and destroy micro-organisms, is stored in the memory of the antibody producing cells, and this is what makes us immune to that particular infection. Next time those bacteria enter our body, they will be destroyed immediately and no longer can make you ill. This acquired immunity will not only result from an infection; it can also be induced by vaccination.
A vaccine is a weakened, killed or incomplete form of a micro-organism that cannot cause disease, but will result in the production of antibodies when it is injected in our body. As a consequence, the produced antibodies will protect us against that disease. Since our body can make antibodies against viruses and bacteria, we can get vaccines against viral and bacterial infections.
So why don't we vaccinate against all infectious diseases? And why do infectious diseases still exist? Several diseases can be caused by many different kinds of the same sort of bacteria. For instance, traveler's diarrhea is often caused by E. coli, but there are many different forms of E. coli, and when you have had one (which may have been bad enough to spoil your holiday) you are not yet protected against the rest. In that situation vaccination is not very efficient. Moreover, some bacteria are smart enough to evade our antibodies. They change their 'looks' constantly, so that antibodies produced to one variant are useless towards the next. When antibodies are powerless, vaccines are as well. And there is an economic aspect: vaccination is expensive, and especially in developing countries it is not possible to reach the majority of the population with vaccination programs. Vaccination is not completely without risk, and it would be unwise to inject everybody with all available vaccines, when the majority of those people have very little risk to ever get most of these infections. So when you live in a moderate climate, you will not be vaccinated against tropical diseases, unless you plan to travel in the tropics. Check out vaccination recommendations for travellers (source: CDC). And finally, for many infectious diseases a vaccine is not (yet) available. Vaccine development is one of the major research areas in medical microbiology