Wikipedia has a timeline on this:
http://en.wikipedia.org/wiki/Moria_(Middle-earth)
Short version:
- The dwarves lived in Moria during ancient times but they dug too deep and found the Balrog.
- Because of the Balrog, the dwarves were forced to evacuate Moria and resettle in Erebor (which is later sacked by the dragon Smaug).
- After being driven from Erebor by Smaug, a group of dwarves try to re-take their former home of Moria which had since been occupied by orcs. This is the flashback battle scene from The Hobbit movie. The dwarves won the battle, but they lost too many and lacked the strength to face the Balrog, forcing them to abandon their plans of resettling in Moria.
- Some time between the events of The Hobbit and LOTR, the dwarf Balin (a cousin of Gimli and one of the 13 dwarves featured in The Hobbit book/film) led a group of dwarves to recapture Moria. They were initially successful at establishing a colony in Moria (hence why Gimli thought they would be greeted warmly), but their settlement was eventually destroyed by orcs, an event unknown to the outside world.
- After Gandalf defeated the Balrog, the dwarves were finally able to fully resettle Moria following the events of LOTR.