Inevitably, there will be a place that either encourages the pirates to attack enemies, permits pirates and has "neutrality" to take advantage of their wealth, or is actively ruled by pirates to guarantee a safe harbor.
Pirates need a legitimizing force, so many were privateers. They operated under the aegis of a state and were essentially pirates against a particular nation. In this case, they typically operated out of the ports of the legitimizing state. Division among governments, lack of communication, religious differences (like with the Barbary pirates) or just greed make many nations look a blind eye to piracy as long as the profits were spread around.
Lacking legitimacy, the pirates needed a place to supply, somewhere to spend their loot, and a means of selling their loot to legitimate buyers so they could make money (and possibly build a reputation as "merchants" to give them somewhere to retire to). Small nations or island-states could make deals with pirates, who could help guarantee their safety from enemies in exchange for port access. These cities could also be legitimately afraid of being attacked by the pirates if they didn't cooperate.
These small states would profit from the gambling, drinking, and prostitution supported by fleecing the pirates for all they were worth. Unscrupulous merchants needed a semi-legitimate reason to stop at these ports so they could buy the pilfered goods at a discount and resell those goods to destinations willing to overlook the potential seedy origins in exchange for cheap goods.
Then they need to be a workable distance from trade routes and towns they could attack. Too close, and they invite counter-attack. Too far, and they waste their time going back and forth traveling. So Madagascar, for example, was a pirate haven for raiding the Indian Ocean. The locals were unmolested by the pirates, who needed their cooperation. It was also part-way to Europe and the Americas, so merchants could buy the goods and ship them on to places that weren't too picky about where they got things.
Temporary bases close to targets could allow pirates to at least get some goods (like food, water, and/or wood) while raiding, but also be temporary enough that the authorities didn't know where the pirates were. Then they could travel back home (far from where they were pirating) and enjoy the fruits of their work without having their actions associated with piracy.
And finally, the pirates can pretend to be legitimate ships with legitimate aims. Maybe they even are! A merchant ship with an unscrupulous captain might ship goods when there are goods to ship, but raid when they think they can get away with it. Many navies underpaid their crews and captains, so a war ship might conduct attacks (especially on hostile or at least neutral) shipping with little risk of getting in trouble - after all, THEY might be the ones dispatched to hunt for the pirates.