Measurements of the double-differential π± production cross section in the range of momentum 0.5⩽p⩽8.0 GeV/c and angle 0.025⩽θ⩽0.25 rad in collisions of protons on beryllium, carbon, nitrogen, oxygen, aluminum, copper, tin, tantalum, and lead are presented. The data were taken with the large-acceptance HAdRon Production (HARP) detector in the T9 beamline of the CERN Proton Synchrotron. Incident particles were identified by an elaborate system of beam detectors. Thin targets of 5% of a nuclear interaction length were used. The tracking and identification of the produced particles were performed using the forward system of the HARP experiment. Results are obtained for the double-differential cross sections d2σ/dp dΩ mainly at four incident proton beam momenta (3, 5, 8, and 12 GeV/c). Measurements are compared with the GEANT4 and MARS Monte Carlo generators. A global parametrization is provided as an approximation of all the collected datasets, which can serve as a tool for quick yield estimates