Gollum has been following Frodo and Sam since they left Rivendell for the Ring quest, but they finally catch him in Emyn Muil.
Gollum agrees to help Frodo get into Mordor as long as Frodo does not tie Gollum up or hurt him.
One thing is certain: Gollum is absolutely certain he does not want the Ring to fall into the hands of Sauron.
So when Frodo starts to approach the Black Gate of Mordor, Gollum stops him. He wants to save Frodo from Sauron (so long as Frodo is carrying the Ring), and offers to bring Frodo to Mordor by another, secret way—a high mountain pass called Cirith Ungol.
Frodo agrees to go, but Sam is suspicious, especially after he overhears Gollum arguing with himself: his good self ("Slinker") wants to help Frodo, but his bad self ("Stinker") wants to take Frodo to "Her" to be killed so that Gollum can take the Ring.
This struggle between Gollum's good and bad selves continues through their whole journey, but he tips more definitely towards the bad side when Frodo helps Faramir to capture him and lead him away from the pool at Henneth Annûn.
Gollum takes Frodo and Sam to Cirith Ungol, and as they are resting before the final push, Gollum reaches out to Frodo. Unfortunately, that's just when Sam wakes and accuses Gollum of sneaking.
Gollum is shaken out of whatever reflective moment he is having, and resolves to lead them into Cirith Ungol after all.
Just after they enter Cirith Ungol, unsuspectingly, Frodo is attacked by a giant spider named Shelob, and Sam is attacked by Gollum.
Sam fends Gollum off, and the creature manages to escape.
Then, Sam overhears the two orcs who have captured Frodo mention Shelob's "Sneak."
Apparently, that's Gollum, who is well-known to them. He escaped Barad-dûr some time ago, and now Gollum has some kind of deal with Shelob.
It turns out Gollum and Shelob have been in cahoots all along.