Apollo - why the 180 to dock?

Why did the Apollo commend module have to do a 180 to dock with the lander?

For safety and aerodynamic reasons, you want the command module at the top of the rocket. Mounted above this was the launch escape assembly, which would send the module away from an exploding or otherwise failing rocket, allowing the astronauts inside to parachute safely to Earth.
With that constraint in mind, the LM has to be placed underneath it. Since the docking port is at the top of the command module, they had to perform the 180 in order to be facing the LM for docking to take place.

The hatch is on the nose of the command module, and the top needs to have the escape rockets on them if they had to parachute away from the Saturn V in an emergency. The engines on the command module were on the other end, and of course had to be free to fire.

Besides, the command module and lunar module needed to rendezvous and dock after the moon landing. So they needed the docking ports anyway. And if there was a problem with the docking system, it’s probably better to find out right after the launch (when all 3 crew are on the command module) rather than in lunar orbit, with 2 crew members stranded in the lunar module.

One other thing, just my WAG but launching two modules docked together may not be desirable anyway. The vibration during launch would put a lot of stress on the docking port, and I’m not sure if it’s designed for that type of stress.

Fun Fact: early designs of the LEM had the surface EVA hatch be an auxiliary docking port.

There was a contingency plan for the astronauts to transfer between CSM and LM by taking a short spacewalk. On later missions The CSM pilot took a walk on the way home to retrieve film canisters from instruments in the service module that had been surveying the moon whilst he was waiting for guys on the surface to do their stuff. So the capability was always there.

I recall that when I was 13. There was some plan that they would EVA to the LM.

Even if NASA had the astronauts just transfer to the LM via EVA, the Transposition, Docking and Extraction maneuver would still have been necessary. The two modules needed to be connected after the translunar injection burn. From that point, the Service Propulsion System Engine and RCS on the SM were used for course correction and lunar orbit insertion. So, the LM needed to be attached to the CSM. It couldn’t be attached to the same side as the engine for obvious reasons, so that left the other end as the only option. And, for reasons previously discussed, the LM could not be launched already connected to the top of the CM. This would have been less aerodynamic, it would have put fuel above the astronauts, and would have complicated the entire Launch Escape System.
So, what was left after all considerations was the Transposition, Docking, and Extraction (TD&E).

Thank you all for the excellent answers.