Iran won only their second-ever match at a World Cup after a late own-goal gave them victory over Morocco in the opening game.
In the first half, Iran played well and defended strongly and Spain could not score however they dominted the majority of the contest.
Iran was also risky on the break, using the speed of its attacking players to threaten the Spanish back four but without creating many real chances.
But, two minutes after the hour mark, Iran thought they had pulled level when their opponents failed to clear their lines from a freekick, allowing Saeid Ezatolahi to smash home the loose ball.
Spain could not managed to get a second despite their best efforts while Iran nearly scored an equaliser when Mehdi's powerful header hit the crossbar.
Iran coach Carlos Queiroz knows they now face Spain and Portugal in their next two games, but insisted his team can "make the impossible possible".
DF Dani Carvajal, 6 - Starting his first game of any kind since the May 26 Champions League final, Carvajal looked sharp from the off and proved his fitness, although he was rarely involved going forward. It appeared that Beiranvand exaggerated his pain after Costa stood on his foot.
The most naturally gifted player in the Iran squad, Azmoun - who plays his football in Kazan for Rubin - was fairly prominent in attack against Morocco.
"That Iran 94th minute throw-in is now part of my all time best world cup moment", tweeted one fan.
And while goalkeeper Alireza Beiranvand recognises few will fancy Iran to add to their current points tally, he is in a defiant mood and insists Spain will be in for a battle.
It was far from a attractive win, but the goal was enough to make Spain coach Fernando Hierro smile.
On this evidence, the Spaniard certainly seems in fine fettle and naturally seemed to find more of a foothold in this one than he did during the draw with Portugal. Costa replied. "It was during the first half, they were provoking us".
"We were happier after the match against Portugal", he said in his postmatch news conference before straightening up and noting that Spain's position is far from unusual.
You can watch the stream of the match from Kazan Live & Exclusive on beIN SPORTS CONNECT.