Abstract Using the near-IR spectroscopy of the MOSFIRE Deep Evolution Field survey, we investigate the role of the local environment in the gas-phase metallicity of galaxies. The local environment measurements are derived from accurate and uniformly calculated photometric redshifts with well-calibrated probability distributions. Based on rest-frame optical emission lines, [N ii]λ6584 and Hα, we measure gas-phase oxygen abundances of 167 galaxies at 1.37 ≤ z ≤ 1.7 and 303 galaxies at 2.09 ≤ z ≤ 2.61, located in diverse environments. We find that at z ∼ 1.5, the average metallicity of galaxies in overdensities with M * ∼ 109.8 M ⊙, 1010.2 M ⊙, and 1010.8 M ⊙ is higher relative to their field counterparts by 0.094 ± 0.051, 0.068 ± 0.028, and 0.052 ± 0.043 dex, respectively. However, this metallicity enhancement does not exist at higher redshift, z ∼ 2.3, where, compared to the field galaxies, we find 0.056 ± 0.043, 0.056 ± 0.028, and 0.096 ± 0.034 dex lower metallicity for galaxies in overdense environments with M * ∼ 109.8 M ⊙, 1010.2 M ⊙ and 1010.7 M ⊙, respectively. Our results suggest that, at 1.37 ≤ z ≤ 2.61, the variation of mass–metallicity relation with local environment is small (<0.1 dex), and reverses at z ∼ 2. Our results support the hypothesis that, at the early stages of cluster formation, owing to efficient gas cooling, galaxies residing in overdensities host a higher fraction of pristine gas with prominent primordial gas accretion, which lowers their gas-phase metallicity compared to their coeval field galaxies. However, as the universe evolves to lower redshifts (z ≲ 2), the shock-heated gas in overdensities cannot cool down efficiently, and galaxies become metal-rich rapidly due to the suppression of pristine gas inflow and re-accretion of metal-enriched outflows in overdensities.