Sharapova trailed 3-0 in the second set but battled back to 4-3 down before her serve was broken again by the 21-year-old who broke into the top-100 this week.
The pair had never met before and Gavrilova, who is based in Australia, was playing in her first Miami Open.
"I have been dreaming about beating Maria since I was probably 12 when I saw her win Wimbledon, when she beat Serena," said Gavrilova who expects to receive her Australian citizenship later this year.
"I was probably visualising beating her since I was 12 but this was a bit harder than that. I thought I was very composed and just did my best. I was believing."
Sharapova said she had lacked patience at times and attempted too many winners but she was philosophical about her loss.
"It's sport, and I happened to lose the match," she said. "Of course it's a bit of a surprise. I'm expected to win."
Venus Williams eased into the third round with a comfortable 6-3 6-2 win over Poland's Urszula Radwanska while Caroline Wozniacki also progressed.
Williams has been away from competition for almost a month but she needed just 66 minutes to beat the younger sister of 2012 Miami winner Agnieszka Radwanska.
Williams was not at her best, she made 24 unforced errors but produced 22 winners to Radwanska's four and her passage to the next round was never in doubt.
"She's definitely a tricky player. She puts so many balls in play. And it was a little windy today - I just had to keep my feet moving and pray my balls were going in," said Williams, who will face Australian Sam Stosur in the next round after she defeated French qualifier Pauline Parmentier 6-1 3-6 6-0.
Fourth seed Wozniacki had no trouble in dealing with American Madison Brengle 6-0 6-1 to set up a meeting with Estonian Kaia Kanepi.
Agnieszka Radwanska had a tougher battle, surviving a strong test in the second set to earn a 6-4 7-5 win over Slovakia's Anna Schmiedlova.
Top seed Serena Williams will be in action on Friday against Romanian Monica Niculescu, while third seed Simona Halep takes on Czech wildcard Nicole Vaidisova.

Latest News from Sports News Desk