Stay out of harbours then. Apart from a very small handful of daring raids (like the Scapa Flow raid of course), it's not like German U-boats raided Allied harbours on a regular basis.
When reading these forums it sometimes seems like people spent more time infiltrating harbours than wrecking havock along the convoy lanes. But to each his/hers own of course.
rgds/EoE