In The Scarlet Letter, Nathaniel Hawthorne is commenting specifically on a time and place in American history when the Puritans lived. They lived in a theocracy; that is, their civil laws were based on biblical principles and the Bible itself. This novel is specific to the Puritan belief that all sin should be punished publicly, and forgiveness of sins was not an option.
More than that, though, Hawthorne wrote about human nature, the nature of man which is constant throughout time and place. His commentary regarding the need for prisons comes at the very beginning of the book, in chapter 1. He says:
The founders of a new colony, whatever Utopia of human virtue and happiness they might originally project, have invariably recognized it among their earliest practical necessities to allot a portion of the virgin soil as a cemetery, and another portion as the site of a prison.
Simply put, every people in every time who are starting something new--no matter how wonderful and perfect they hope and intend for it to be--must deal with two issues: death and sin. Cemetery and prison.
Much of Nathaniel Hawthorne's writing is both symbolic and allegorical; and, The Scarlet Letter is no exception. In the first chapter of his novel, Hawthorne chooses the setting of the prison and its iron door to represent the terrible restrictiveness of Puritanism that forbade sin, a natural foible of human nature. Since sin is part of the weakness of mankind, and it was forbidden in Puritanism, it was necessary to have the prison. Here lies the irony in Hawthorne's line that whatever Utopia is built, people must yet build a prison and a cemetery. (There is no real Utopia.)
It is especially ironic that a religious sect such as that of the Puritans, who sought the freedom to practice their religion in coming to America, should then, themselves, build a prison before all other buildings. And, this rust and decay and ugliness of the prison forshadow the gloom of the novel. For, as in the works of Charles Dickens, the society in which the characters live, is virtually a prison. Hester is labeled as an adulteress and is ostracized; Dimmesdale is tortured by his guilt about his secret sin, and Chillingworth is destroyed by his malicious acts of revenge against the minister--all are imprisoned in their own way in the restrictive Puritan society.