There’s a huge literature on this, and there’s no one right answer, but…
Where – Medieval Cities developed around pre-existing (usually Roman) cities or settlements, cathedrals and other centers of worship, major castles/the courts of kings and major nobles, significant points on rivers, roads, and passes, and ports.
Why – usually to offer specialized goods and services to a place where permanent or steady demand existed. So at cathedrals you get stonemasons, makers of stained-glass-windows, candlemakers, etc. And those people in turn need brewers and bakers and butchers, etc. Nobles need smiths, tailors, clothmakers, clerks, lawyers, moneylenders, etc. And so and so forth.
How – usually a combination of the gradual accretion of population and the acquisition of a charter.