The first time the body is exposed to a new antigen, building an immune response takes time. The body has to build an antibody that can recognize it, and that requires rearranging genes by trial and error -- a process that takes time. However, once a good antibody has been produced the first time, the body keeps the machinery it needs to reproduce it ready to go. Antibodies can therefore be produced much more quickly after the body has already been taught to recognize an antigen (after an initial infection or vaccination). Vaccines work by telling the body to make antibodies against a disease, so that if a person is ever exposed to that disease, their immune system will already be ready to fight back.
More specifically, vaccines use a substance known as an adjuvant. Adjuvants stimulate the body to produce an immune response against an antigen that is part of the pathogen the vaccine is designed to protect against. Usually the antigen is a surface protein from the bacterium or virus in question.