The increasing accumulation of heavy metals (HMs) due to various human activities is a significant concern. This study has employed 16S rRNA amplicon sequencing and Inductively Coupled Plasma Mass Spectrometry (ICP-MS) spectrometry to investigate HMS concentrations and identify bacterial strains exhibiting resistance to HMS, and used the PICRUSt tool to assess the metabolic pathways of bacterial communities. Our primary focus was to assess HMs concentrations in the soils of Baghdad (BG) and the Baiji Oil Refinery (BOR) area while examining the bacterial diversity in these regions. The results revealed that the average levels of Cadmium (Cd) and Lead (Pb) in BOR were higher than in BG and the global average. In BOR, the most prevalent bacterial genera were Flavobacterium, Shewanella, and Pseudomonas. Using the PICRUSt tool, we identified that Cd and Pb substantially impacted the metabolic pathways of these bacterial communities. This study marks the first report in Iraq to employ 16S rRNA gene sequencing to analyze bacterial communities in Iraqi soil and investigate how HMs affect them. However, this study can serve as a reference for future research and the development of innovative strategies for the sustainable management of soil ecosystems.