The match was a repeat of the London 2012 Olympic final, which Mexico won 2-1.
Brazil, the holders having won gold in their home Olympics in 2016, had the better of the first half, but the second failed to live up to expectations.
The game went to extra time and, while Brazil looked more likely to break the deadlock, the match finished goalless after 120 minutes and it went to spot kicks.
Dani Alves scored Brazil’s first penalty before Eduardo Aguirre saw his spot kick saved. Arsenal forward Gabriel Martinelli then put Brazil 2-0 ahead with a cool penalty and Mexico’s second effort through Johan Vasquez hit the post.