The incident is orchestrated by Daenerys, who had previously been faced with the issue of using a slave army to conquer a realm in which slavery had been outlawed and reviled for centuries.  Having observed the suffering of Astapor's slaves , Daenerys devises a plan to acquire all of Astapor's Unsullied and turn on the Good Masters. She offers one of her dragons in exchange for the Unsullied, as her ship and gold weren't enough for the Good Masters. In the meantime, Daenerys pretends not to understand the constant insults of Kraznys mo Nakloz.
Daenerys springs her trap after handing over Drogon. After making sure that the Unsullied are indeed loyal to her as their new master, she orders them to kill the Good Masters and their soldiers, as well as any man in Astapor who holds a whip. She also instructs them to spare all children and strike off the chains of any slave they came across.
The Good Masters are powerless to stop the situation, as the local defenders are not only outnumbered but also inferior to the Unsullied. Furthermore, Kraznys mo Nakloz had assumed that his new dragon would, like a slave, accept its new master. Daenerys reminds him that dragons are not slaves before commanding Drogon to burn the slaver.
The Unsullied perform as promised, the Good Masters are all slain and the local slaves freed. Immediately after the Sack is completed Daenerys frees the Unsullied as well. They, however, opt en masse to continue their service to her as free men and depart Astapor with her.
In the books
In the A Song of Ice and Fire novels, the Sack of Astapor happens in much the same way, though it begins in the Plaza of Punishment - the novels' equivalent to the Walk of Punishment - because the Plaza of Pride is too small to contain all the Unsullied. Besides the 8,000 Unsullied, Daenerys' bloodriders as well as the rest of her khalasar take part in the sack of the city, although they might have in the TV series as well– it isn't clear since the Sack itself is depicted off-screen. Another difference is that Barristan and Jorah were privy to Daenerys's plan: they and the khalasar attack along with Drogon when Daenerys utters dracarys. Daenerys also orders her forces to spare all children below the age of twelve, the TV version shortens this to just have her say "harm no child" without specifying an age.
- Sack of Astapor (spoilers from the books)