There are useful and pathogenic bacteria in our body. How does the immune system differentiate between them?
Pathogens will often have non-peptide antigens, peptide antigens, and pathogen-associated molecular patterns that are recognized by innate and adaptive immunity mechanisms. Useful bacteria are not differentiated, and often sit beyond the grasp of our immune system, or have mechanisms to escape an immune response. When contacted they do, however, produce an immune response and due to their location, this often involves mucosal immunity:
This portion of the immune system varies greatly in response to the systemic immune response because it is constantly stimulated, and in a way trained, by the presence of all microbes, such as gut flora. As a result, it often resolves infection quickly with low severity, and little lasting tissue damage. Keep in mind that self cells have mechanisms which desensitize them to autoreactivity with immunity. Microbes don't share these same mechanisms, but can evade or escape the immune response through their own methods. But by no means are microbes of any sort, for the average immune system, disregarded.
Unfortunately, to respond more specifically would go into textbook chapters of material so to that end I'm going to cut the explanation here, and recommend you do some research of your own.