As a Magikarp, Gyara belonged to Misty. Team Rocket stole Gyara from Misty. They possibly injected him with a fluid to force evolution.
Blaine later reveals that he did, in fact, use Gyara as an experiment.
Gyara either escapes from or is released by Team Rocket. Misty tracks him down and tries to recapture him. Gyara badly injures Misty's Staryu, but Red interferes with his Bulbasaur. He captures Gyara and gives it to her when he finds out that he belonged to Misty.
Later, Misty and Gyara come to Red's rescue, saving him from a wild Dragonite in a battle of titans. Misty trades Gyara for Red's Krabby because Red doesn't have any Pokémon who know Surf.
Red's Pokémon remember Gyara from when he rampaged and they refuse to trust him. Over the course of a struggle against Team Rocket's Muk, and to protect Articuno, they forge new bonds of trust and friendship.