The Duox-reactive oxygen species (ROS) system and the immune deficiency (Imd) pathway play a major role in insect gut immunity. However, their interaction to accomplish an effective immune response is still unclear. Here, we show that Duox regulates the peritrophic matrix (PM) and further affects the Imd immune response to pathogens in Bactrocera dorsalis. This regulation requires a nuanced ROS balance: low H2O2 increases PM permeability, while higher H2O2 damages the PM during infection. Importantly, we found that gut commensal bacteria ensured proper Duox-dependent ROS production and PM stability, thus preventing Imd pathway overactivation in response to pathogens. We conclude that gut commensal bacteria-induced Duox-ROS is crucial for maintaining PM structural homeostasis, and the PM, in turn, regulates Imd pathway activation and protects intestinal epithelial cells. Thus, our study reveals a crosstalk between the PM barrier and Imd-mediated antibacterial function to ensure host defense in the gut.