Anna Karenina was written over the course of four years, from 1873 to 1877, and then published in book form in 1878. Tolstoy wrote the book in serial form, which means that he would write installments that would be published in a magazine (The Russian Messenger) on a monthly basis.
Tolstoy's novel has a complicated back story. Money was an important concern for Tolstoy, and the the novel became a significant financial success. Beyond that, Tolstoy used the novel to explore different ideas or issues that he cared about. These included the "Europeanization" of Russia, the plight of emancipated peasants, and the issues of adultery and women's rights.
Another story is that Tolstoy found his way into the novel because of one of his children, who left a copy of Pushkin's Tales of Belkin on a windowsill for Tolstoy to find. Pushkin's economical approach to story telling inspired Tolstoy.
Nevertheless, Tolstoy found if difficult to formulate a story that would include all the themes he wished to write about, and his writing of it was plagued by constant interruptions. But when he finally completed the book in 1877 and published it the following year, it was a tremendous success, and helped cement his position as one of Russia's greatest authors.