Spain had been allied with France against the United Kingdom since the Second Treaty of San Ildefonso in 1796. After the defeat of the combined Spanish and French fleets by the British at the Battle of Trafalgar in 1805, cracks began to appear in the alliance, with Spain preparing to invade France from the south after the outbreak of the War of the Fourth Coalition.
In 1806, Spain readied for an invasion in case of a Prussian victory, but Napoleon's rout of the Prussian army at the Battle of Jena-Auerstaedt caused Spain to back down. However, Spain continued to resent the loss of its fleet at Trafalgar and the fact that it was forced to join the Continental System. Nevertheless, the two allies agreed to partition Portugal, a long-standing British trading partner and ally, which refused to join the Continental System.
Napoleon was fully aware of the disastrous state of Spain's economy and administration, and its political fragility. He came to believe that it had little value as an ally in the current circumstances. He insisted on positioning French troops in Spain to prepare for a French invasion of Portugal, but once this was done, he continued to move additional French troops into Spain without any sign of an advance into Portugal.
The presence of French troops on Spanish soil was extremely unpopular in Spain, resulting in the Tumult of Aranjuez by supporters of Ferdinand, the heir apparent to the throne. Charles IV of Spain abdicated in March 1808 and his prime minister, Manuel de Godoy was also ousted. Ferdinand was declared the legitimate monarch, and returned to Madrid expecting to take up his duties as king. Napoleon Bonaparte summoned Ferdinand to Bayonne, France, and Ferdinand went, fully expecting Bonaparte to approve his position as monarch. Napoleon had also summoned Charles IV, who arrived separately. Napoleon pressed Ferdinand to abdicate in favor of his father, who had abdicated under duress. Charles IV then abdicated in favor of Napoleon, since he did not want his despised son to be heir to the throne. Napoleon placed his brother Joseph on the throne. The formal abdications were designed to preserve the legitimacy of the new sitting monarch.