Portugal got off to a dream start with Cristiano Ronaldo opening the scoring in the third minute through a penalty after he was brought down inside the box by Nacho, 1-0.
Spain only started getting their rhythm after a quarter of an hour but were vulnerable to counter-attacks.
Diego Costa equalised for La Roja in the 24th minute by shrugging off three defenders inside the box before smashing the ball into the bottom corner.
Andres Iniesta almost made it 2-1 for Spain in the 35th minute with a low diagonal shot from the edge of the box that missed slightly wide.
Ronaldo restored the lead for Fernando Santos’ troops on the stroke of halftime with a low strike just outside the box that should have been an easy catch for David De Gea but the Spanish goalkeeper spilled the ball into the back of the net, 2-1.
Costa got Spain back into the game again ten minutes into the second stanza with a simple but rugged tap in following chip into the area, 2-2.
Nacho sent La Roja ahead four minutes later with a cracking strike on the half-volley that went in off the crossbar.
Costa almost completed his hat-trick for Spain 20 minutes before time with a left footed strike inside the box after going through but his effort missed wide.
Portugal were applying the pressure with ten minutes to go but they could not really penetrate La Roja who were compact at the back.
Ronaldo got his hat-trick and the equaliser two minutes before time with a fantastic free-kick that looped over the wall and sailed into the top corner.
After the first round of matches in Group B, Iran top the standings followed by Portugal and Spain, while Morocco are rooted to the bottom.
Portugal: Rui Patricio, Cédric, Pepe, Fonte, Guerreiro, Bernardo Silva, William Carvalho, Moutinho, Bruno Fernandes, Cristiano, Guedes.
Spain: De Gea; Nacho, Pique, Ramos, Alba; Koke, Busquets; Silva, Isco, Iniesta; Diego Costa.