Striker Youssef En-Nesyri scored the winning goal in the first half, leaping highest to beat goalkeeper Diogo Costa to the ball and heading in to spark pandemonium at Al Thumama Stadium.
The north African side’s supporters populated most of the venue and joyously celebrated their breakthrough moment for their continent on the global stage.
Ronaldo came off the bench in the 50th minute to equal the men’s all-time appearance record of 196 in international matches, but he could not drag his side back into the contest.
Morocco were happy to play on the counter and grabbed the opener just before the break when En-Nesyri headed in from Yahya Attiyat-Allah’s cross.
Portugal skipper Bruno Fernandes came agonisingly close to levelling just minutes later but a brilliant individual effort struck the crossbar.
Decimated by injuries, Morocco sat back for the majority of the second half and Yassine Bounou brilliantly tipped over Joao Felix’s drive – the closest they came to an equaliser.
Morocco striker Walid Cheddira was sent off for a second yellow card in eight minutes of additional time but Portugal could not find the equaliser as their last-four hopes were dashed.