The Germans, gold medalists twice and bronze winners once in the past three Olympics, twice built three-goal leads at a packed University of the Witwatersrand hockey stadium.
But goals from Austin Smith, making his 150th international appearance, and Jonathan Robinson for South Africa set up a tense finish to the Pool B game.
Germany had a fifth goal disallowed and their goalkeeper, Mark Appel, pulled off a brilliant left-hand parry to prevent an equaliser off a last-minute penalty corner.
South Africa were left to lament not translating first-half superiority into goals and then being caught out just before and after half-time when conceding three goals.
The second German goal on 32 minutes was the best of the match as flier Niklas Wellen ran along the baseline and when his shot was blocked, he regained possession and scored.
“I am gutted that we lost in front of a fantastic crowd,” admitted Smith, “but I am proud of the effort put in by a team with many youngsters.”
Team-mate Jethro Eustice said: “We have got to become more clinical in the circle so that we are not chasing games as happened against Ireland and Germany.”
Ireland needed a 59th-minute goal from Shane O’Donoghue off a penalty corner to edge improving Egypt 2-1 in the same section.
After being humiliated 10-0 by Belgium, the north Africans restricted Germany to five goals and the goal against Ireland was their first of the tournament.
Leaders Belgium, Germany and Ireland have six points and are through to the quarter-finals, leaving South Africa and Egypt to battle for the other place.
Hockey World League title-holders Australia scored twice in the final eight minutes to beat stubborn Spain 2-0 in a cat-and-mouse clash that produced few scoring chances.
Dylan Wotherspoon, who plays club hockey for the Gold Coast-based Labrador Tigerstix, broke the deadlock by diverting a cross between the legs of veteran goalkeeper Quico Cortes.
Spain hotly disputed the second goal, scored by Trent Mitton via a close-range smash, put the video referee gave his approval.
“It was a closer match than the scoreline suggests,” conceded Wotherspoon. “We knew it would not be easy against the Spaniards and that is exactly how it turned out.”
Team-mate Jeremy Hayward said: “We stuck to our game plan against very defensive opponents and victory brings a measure of revenge for our loss to Spain at the Rio Olympics.”
After a draw with New Zealand and a narrow loss to Australia, France triumphed 4-1 against Japan to secure a last-eight place.
As in their previous matches, the French played hockey that was a joy to watch and led 2-1 at half-time before sealing success with goals in the third and final quarters.
“We have talent and work hard,” said Pieter van Straaten, “and when you match the two you produce magic. France are capable of amazing things.”
Australia, France and New Zealand have secured last-eight slots and Spain need one point to be certain of joining them at the expense of Japan.
AFP / Expatica