Pervez Musharraf, the onetime military ruler of a nuclear-armed Pakistan who promised critical support for Washington’s campaign against Al Qaeda after the attacks of Sept. 11, 2001, but faced growing resistance at home in a land seething with anti-Western passions, died Sunday. He was 79.

His death was confirmed by Lt. Gen. Sahir Shamshad Mirza, the head of the joint chiefs of staff of the Pakistani military. He died in a hospital in Dubai, United Arab Emirates, where he was being treated for a long illness, state media reported.

From the moment he took power in a bloodless coup in late 1999 to his resignation and self-exile under threat of impeachment in 2008, Mr. Musharraf offered the world the swashbuckling image of a former army commando and ally of the United States who guaranteed a measure of regional stability in the upheaval after 9/11 and the subsequent United States attack on Afghanistan.

But Washington’s demands for firm action against Islamist militancy collided with competing pressures from Pakistani Muslims who were resentful of Mr. Musharraf’s close ties to Washington.

Indeed, Mr. Musharraf’s efforts to maintain a measure of democracy while ruling as an authoritarian, and to promote secularism in a country where religious radicals wielded broad influence, brought him few friends and a growing roster of enemies.

By the time he suspended the Pakistani Constitution and imposed emergency rule in late 2007, the patience of President George W. Bush, who had once called him a “courageous leader and friend of the United States,” was wearing thin.

Yet even in exile, Mr. Musharraf continued to see himself as a potential savior. In 2013, he returned to Pakistan with the hope of regaining power as a civilian at the ballot box. However, he encountered an array of criminal charges, as well as broad indifference among Pakistanis who might once have supported him.

Within a year, he was barred for life from running for public office. And a year after that, a special court indicted him on treason charges, which he denied, and eventually sentenced him to death, though the ruling was later overturned by the country’s High Court.

The indictment seemed to represent a shift for Pakistan, where no previous military ruler had been tried for abuse of power. But in March 2016, before a trial could get underway and in what seemed to be a trade-off between the powerful military and the civilian government, he slipped out of the country, ostensibly to seek medical treatment in Dubai. By then, his once pervasive role in Pakistan’s political life had been reduced to appearances on a television talk show.

Mr. Musharraf’s time as president highlighted many of the paradoxes of his land. American officials became increasingly frustrated with what they viewed as his refusal to crush terrorist groups that maintained bases and training camps in tribal areas of Pakistan. That the leader of Al Qaeda, Osama bin Laden, was widely believed to be living in those areas after his escape from Afghanistan in 2001 only intensified American anger.

When U.S. Navy SEALs finally located and killed Bin Laden in 2011, the Qaeda leader was hiding in a safe house in Abbottabad, just a few hundred yards from Pakistan’s top military academy, apparently shielded by elements within the country’s intelligence community. American officials said that Bin Laden had been living there for five years.

Such ambiguities permeated Mr. Musharraf’s relationship with American officials. Because he was generally pro-American, and because he seemed far preferable to any other possible Pakistani leader, the Bush administration strongly supported him. During his years in power, the United States provided Pakistan with aid worth more than $1 billion a year. Most was military.

Yet every time Mr. Musharraf made even a tentative effort to crack down on foreign fighters from the Taliban and Al Qaeda, radicals and fundamentalists at home — often led by religious leaders — staged mass protests. Denouncing him as a lackey of the Bush administration, adversaries nicknamed him “Busharraf.”

The conflict reached a climax in July 2007 at a redoubt known as the Red Mosque in Islamabad, the capital, when Mr. Musharraf ordered troops to attack Islamists who held sway there. About 100 people died.

The fundamentalist opposition was a question not only of policies but also of personality. Mr. Musharraf was scorned as having adopted a Western lifestyle. An avid sportsman who favored squash, badminton, golf and sailing, he had a reputation as a bon vivant.

He was sometimes photographed with his two Pekingese dogs, ignoring Islamic teachings that dogs are impure and should not be kept as pets.

In his spare time, he played bridge and devoured books on military history. In a land more used to obfuscation, he had “a horrible habit of unexpected candor,” according to Salman Haider, a former chief of India’s diplomatic corps.

Mr. Musharraf also faced questions about his handling of Abdul Qadeer Khan, Pakistan’s top nuclear scientist, who was regarded as a national hero by many of his compatriots for pioneering a nuclear capability to match that of India. In 2004, Dr. Khan admitted that he had been running an illicit and lucrative network to spread nuclear technology to North Korea, Iran and elsewhere.

Pressed by Washington to take stern action, Mr. Musharraf placed Dr. Khan under house arrest. But he then pardoned him when, in what opposition politicians called a trade-off, Dr. Khan publicly admitted to taking full and exclusive responsibility for running the network.

In 2004, in an interview with The New York Times, Mr. Musharraf said that he had been concerned for several years that an investigation of Dr. Khan could provoke a political backlash. “It was extremely sensitive,” he said. “One couldn’t start investigating as if he’s any common criminal.”

Pervez Musharraf was born on Aug. 11, 1943, into an Urdu-speaking family in Delhi, when the Indian subcontinent was still under British rule. During the partition riots of 1947, his family fled to what became Pakistan.

His mother, Zarin Musharraf, worked as an academic. His father, Syed Musharraf, who had been a civil servant during the last years of British rule, joined Pakistan’s incipient diplomatic corps. In 1949, Syed Musharraf was sent to Turkey.

After seven years there, the family returned to Pakistan, where Pervez attended St. Patrick’s High School in Karachi and Forman Christian College in Lahore.

His time in Turkey, then regarded as the most secular country in the Islamic world, left a deep impression, and he later cited Mustafa Kemal Ataturk, the Western-oriented founder of the Turkish Republic, as his “most admired person.”

Mr. Musharraf entered the Pakistan Military Academy in 1961 and three years later joined an artillery regiment. He also studied at the Royal College of Defense Studies in Britain. In 1968, he married Sehba Farid, who came from a family of Urdu poets. They had a son, Bilal, and a daughter, Ayla.

Because Mr. Musharraf was a muhajir, or emigrant from India, he was able to rise above Pakistan’s ethnic and political divides, which sometimes pit Pashtuns, Punjabis and others against one another.

As a young officer, Mr. Musharraf saw action in Punjab during the 16-day war that Pakistan fought with India in 1965 and was decorated for bravery. He was a commando in an elite unit during the 1971 civil war that produced the breakaway nation of Bangladesh. In 1999, he directed a military incursion into the Kargil region of Indian-controlled Kashmir.

Mr. Musharraf was serving as the military chief of staff when, in the 1990s, he came to detest the two politicians who then dominated Pakistan, Benazir Bhutto and Nawaz Sharif. It was against the political establishment they represented that Mr. Musharraf, by then a general, staged his epochal coup on Oct. 12, 1999.

On that day, he was in Sri Lanka for a series of military meetings sandwiched around several rounds of golf. There he received news that Mr. Sharif, the prime minister who had appointed him to his post but from whom he had become estranged, planned to fire him. Mr. Musharraf resolved to fly home to confront Mr. Sharif, but when his plane approached the airport in Karachi, controllers radioed that they were under orders not to allow it to land.

Mr. Musharraf ordered it to land anyway. By that time, other rebellious officers had seized the state-owned television station and the president’s residence. Emerging from the plane looking dazed and disheveled, Mr. Musharraf realized that he was now his country’s leader.

He later arranged a trial at which Mr. Sharif was convicted of hijacking, kidnapping, attempted murder and treason, and sentenced to life imprisonment. Less than a year later, responding to appeals from the Saudi royal family, Mr. Musharraf pardoned Mr. Sharif and allowed him to leave the country.

Some changes that followed Mr. Musharraf’s coup were immediately palpable. Crime dropped sharply. Police officers stopped pulling cars over to demand bribes. Even airport taxi lines became orderly. And Mr. Musharraf embraced liberal economic policies that impressed business leaders and led to remarkable economic growth.

The army remained fundamental to his power. Pakistani analysts agreed that as long as he was able to maintain a measure of social peace and bring home huge amounts of military aid from the United States, the army would support him.

Regionally, Pakistan was a prime sponsor of the militant Taliban movement, which seized power in Afghanistan in 1996, and Mr. Musharraf continued that support. In January 2000, President Bill Clinton warned that Pakistan was in danger of being added to the American list of countries supporting terrorism.

In 2001, as Americans prepared to attack Afghanistan, Mr. Musharraf tried to broker a peaceful settlement. When his efforts failed, he threw in his lot with the United States and backed the American campaign that forced the Taliban from power.

Mr. Musharraf also set out to find a peaceful solution to the Kashmir dispute. He met several times with Indian leaders and agreed with them on measures to reduce tensions. In 2004, before a thrilled television audience of several hundred million, the two countries played their first cricket match in 15 years.

On Jan. 12, 2002, Mr. Musharraf made a televised speech in which he offered a grand vision for Pakistan. He said it should be a “dynamic Islamic state” in which religion would guide private morality but not public policy.

Militants were quick to respond. Less than two weeks after the speech, they kidnapped a Wall Street Journal reporter, Daniel Pearl, whom they later beheaded. Soon afterward, they attacked a church near the United States Embassy in Islamabad, killing five people, including two Americans.

In August 2002, Mr. Musharraf announced that he had unilaterally added 29 articles to the Pakistani Constitution, including ones that gave him power to dissolve Parliament and fire prime ministers. He also organized a referendum on whether he should be allowed a five-year term as president. He won with 98 percent of the vote, but critics said it was a sham.

Parliament voted to allow Mr. Musharraf to remain on active military duty while serving as president, which is forbidden under Pakistani law. That dispensation was valid until he resigned from the military in late 2007, shortly after declaring a state of emergency.

Seeking to rebut charges that he had become a puppet of Western powers, Mr. Musharraf refused to give American troops permission to operate in regions of Pakistan that border on Afghanistan.

In 2006, he reached an agreement with tribal leaders in the turbulent Waziristan region, where the Taliban and other militant groups had a strong presence. He agreed not to send the army there as long as tribal soldiers policed the region. Critics said that this accord turned Waziristan into a “state within a state” where terrorists could operate freely.

News reports, however, suggested that Mr. Musharraf covertly allowed American and British commandos to stage raids aimed at capturing Taliban or Qaeda fighters.

In March 2007, Mr. Musharraf demanded the resignation of the chief justice of the Supreme Court, Iftikhar Muhammad Chaudry, charging him with abusing his office. The demand set off fierce mass protests, led by lawyers, in what was widely interpreted as an explosion of pent-up grievances. One retired general, Talat Masood, said after the demonstrations that protesters were telling the government, “This one-man show cannot continue.”

Mr. Musharraf soon tried a new gambit: He opened contacts with the country’s two previous civilian leaders, Ms. Bhutto and Mr. Sharif, who were both in exile. When Mr. Sharif tried to enter Pakistan in September 2007, however, he was turned back. Ms. Bhutto returned that October and was assassinated two months later.

Mr. Musharraf’s ill-fated effort to return to power from exile in 2013 was haunted by the legacy of his term in office.

In a country then led by Nawaz Sharif, whom he had ousted in 1999, Mr. Musharraf arrived to face a battery of charges stemming from the deaths of Ms. Bhutto and of a nationalist politician, Akbar Khan Bugti; the siege of the Red Mosque; and the suspension of the Constitution in 2007. He referred to treason charges as “a political vendetta.”

“Having done so much for the development and welfare of the people,” he asked, “is this what I deserve?”

Salman Masood contributed reporting.