The immune system is capable of recognizing pathogenic ("bad") bacteria, either by components of the innate (non-specific) or adaptive (specific) immune system. Pathogenic bacteria will have antigen on their surface that mark them as 'foreign', leading to an immune response targeted to the bacteria. In contrast, the immune system tolerates the normal flora of the body. The precise role that the human immune system takes in tolerating and regulating the populations of the normal flora is not known, it is currently a hot area of research.
Current research suggests that microbiota induces host immune tolerance to commensal bacteria directly via a microbe-associated molecular pattern (MAMP) and polysaccharide (PSA) signalling. The immune system continuously monitors the resident microbiota, and certain antimicrobial mechanisms are constitutively engaged to prevent overgrowth of the colonizing microbes: this maintains what is loosely called immune homeostasis. The mechanisms that control (intestinal) tolerance include those that:
1) minimize exposure to and 2) immune recognition of intestinal microbiota, and 3) those that down-regulate immune responses through intra-cellular and inter-cellular mechanisms.
Research has shown that he tolerance of the normal microbiota of the gut seems to require an extensive network of regulatory immune cells including Tregs and (tolerogenic) dendritic cells.
Thymus-derived Tregs were discovered by Dr. Leszek Ignatowicz to be a crucial player involved in "educating" the immune system about the diverse bacterial colonies in the intestinal flora of mice. In response to the diversity of gut bacteria found in the gut, the Tregs express a 'repertoire T cell receptors' (TCR) that recognize the antigens characteristic of individual bacterial colonies in the gut. Upon engagement of these receptors, Tregs suppresses the adaptive immune response, specifically through the release of immune-modulatory cytokines such as interleukin-2. Moreover, it was found that gut bacteria can also be recognized and protected by a distinct innate lymphoid cell population (ILC) in the intestinal lining of mice. These cells behave like antigen presenting cells, and can recognize and present antigens from gut bacteria through the major histocompatibility complex class II (MHCII). But rather than activating CD4+ T lymphocytes through MHCII engagement, these ILC works by suppressing CD4+ T lymphocytes through MHCII engagement. CD4+ T lymphocytes are involved in clearing pathogen/bacteria, and thus the suppression of CD4+ T lymphocytes is involved in the immune-tolerance of normal flora.
http://www.sciencedirect.com/science/article/pii/S2352345X14000083
http://www.ncbi.nlm.nih.gov/pmc/articles/PMC4007055/