The Quest of EreborEdit
"The Quest of Erebor" in Unfinished Tales elaborates upon the story behind The Hobbit. It tells of a chance meeting between Gandalf and Thorin Oakenshield, Thráin's son, in the inn of the Prancing Pony in Bree. Gandalf had for some time foreseen the coming war with Sauron, and knew that the North was especially vulnerable. If Rivendell were to be attacked, the dragon Smaug could cause great devastation. Thorin was also keen to regain his lost territory, and so the quest was born.
In T.A. 2941, Gandalf arranged (and frequently accompanied) a band of thirteen dwarves and the Hobbit Bilbo Baggins to reclaim from the dragon Smaug the Dwarves' lost treasure in Erebor. To the quest, Gandalf contributed a map and key to Erebor. It was on this Quest of Erebor that Gandalf found his sword, Glamdring, in a troll's treasure hoard, and that Bilbo found the One Ring, in a chance meeting with the creature Gollum (though at the time it was thought to be a lesser ring).
After escaping from the Misty Mountains pursued by Goblins and Wargs, the party was carried to safety by the Great Eagles. Gandalf then persuaded Beorn — who did not like uninvited guests or dwarves — to house and provision the company for the trip through Mirkwood.
Gandalf left the company before they entered Mirkwood, saying that he had pressing business to attend to. He turned up again, however, before the walls of Erebor disguised as an old man, revealing himself when it seemed the Men of Esgaroth and the Elves of Mirkwood would fight Thorin and the Dwarves over Smaug's treasure. The Battle of the Five Armies ensued when hosts of Goblins and Wargs attacked all three parties. After the battle, Gandalf accompanied Bilbo back to the Shire, revealing at Rivendell what his pressing business had been: Gandalf had once again urged the Council to evict Sauron, since quite evidently Sauron did not require the Ring to continue to attract evil to Mirkwood. Then, in an event only briefly described (in The Silmarillion, The Hobbit, and The Lord of the Rings), the Council "put forth its power" and drove Sauron from Dol Guldur. Sauron, however, had anticipated this and withdrew as a feint, only to reappear in Mordor.