Is there a way to prevent bacterial pneumonia?

You can reduce your. Risk of pneumonia by getting your yearly flu vaccine. Also if you are an appropriate candidate, get your pneumonia vaccine every 5 years. If you are immunocompromised, avoid visiting sick patients.
Vaccine for strep. Taking care of oneself with proper exercise, avoiding obesity, not smoking lowers ones risk because pneumonia often affects those with underlying chronic medical illnesses. So avoiding things like smoking which predispose to chronic illnesses like emphysema lowers your risk. Beyond this there are vaccine that lower the risk for particular kinds of pneumonia. Flu shot, and "pneumovax" for ex.