"Master threw it, and Dobby caught it, and Dobby -- Dobby is free."
-Dobby upon receiving a sock (CS18)
He is freed when Harry tricks Lucius Malfoy into throwing him a sock (CS18).
Note that as long as Dobby was the slave of the Malfoys, his attempts to help Harry failed:
the stolen Owl Post (CS1),
the closed magic portal leading to Platform 9 ¾ (CS2),
the enchanted Bludger (CS5, CS10).
But after Harry Potter freed Dobby from the Malfoys, Dobby:
knocked Lucius Malfoy down a flight of stairs (CS18),
gave Harry Gillyweed so he could breathe underwater and rescue Ron (GF26),
he explained how and where Harry could find the Room of Requirement (OP18),
and warned the members of the DA when Umbridge discovered their secret (OP27),
tailed Draco (HBP19, 21),
Apparated into the Malfoy Mansion on a rescue mission from Aberforth (DH23),
Rescued Luna, Dean Thomas and Ollivander from an "escape-proof" cellar (DH23),
Dropped a chandelier on Bellatrix (DH23),
Stripped Narcissa of her wand (DH23),
Rescued Griphook, Harry, Ron, and Hermione from certain death (DH23).
Socks become extremely important to Dobby, symbolizing empowerment and freedom, the rewards for his service to Harry. In Book 4, Dobby begins knitting socks with wool purchased with his wages. For Christmas that year he made Harry a mis-matched pair. Throughout the books, Dobby wears or owns:
- the black "slimy" one Harry gave him (GF11),
- a mustard yellow pair from Harry (GF23),
- a violet pair from Ron (GF23),
- multiple pairs of lurid socks purchased by Harry in Hogsmeade (GF27),
- socks Hermione made and left for the Hogwarts house elves (OP18).