Did they start building vertically?
A common misconception about walled cities is that dense constructions were built right up against the walls. Although the city centers were almost always dense and crowded, it was common for there to be open spaces like gardens and orchards between the city walls and the inhabited center.
I wrote about population density within the walls of Renaissance Florence here and also wrote about wall construction in some Italian cities here.
I know your question is "like" Jerusalem and so you mean to cover this more generally, but in the case of Jerusalem specifically a few things are worth noting:
Walled cities would limit their expansion with, well, walls.
Jerusalem, for instance had its walls and the seven (six functional) gates to lead people in and out of the city. As u/cptbuck specified, the walls were rebuilt in the 16th century, but the new structures wouldn't have compressed the size of the city and reduced its area. Jerusalem still had other parts of the city that we read of in the Bible such as the Garden of Gethsemane and the Mount of Olives that were outside the city walls.
Based on historical description, Golgotha, where Jesus was crucified was an open space but when you visit the Church of the Holy Sepulchre, there is no sign of a hill. This seems to indicate that even 2000ish years ago, there was tons of space within and outside the walls of the city for expansion and to accommodate more people.
At a macro level, the human population globally remained under the 300 million mark until the 13th century, resulting in less pressure for expansion in walled cities to adjust for population growth.