Late last year, as Islamic State fighters battled to expand their stronghold on Libya’s coast, ­militants came within 45 miles ­of the country’s sole remaining ­chemical-weapons site, unnerving Libyan and American officials who feared that potentially deadly chemicals could fall into extremist hands.

In May, when the fighters struck a mile from the lightly guarded desert facility, killing two security officers at a checkpoint, they decided it was time to act.

The Islamic State’s encroachment on an installation outside the remote oasis town of Waddan, where 500 metric tons of ­chemical-weapon precursor materials were stored, set off a hurried chain of events culminating in a disarmament operation involving the United States, European countries and the United Nations.

The international effort, which concluded last week when a Danish ship unloaded the materials at a German port for destruction, is one of the rare successes that Western nations can claim in Libya since dictator Moammar Gaddafi’s ouster in 2011 pitched the North African country into lawlessness and civil war.

[In Libya, the Islamic State’s black flag rises by the Mediterranean]

The mission was also a sign of the risks posed by vulnerable chemicals, even if they have not been weaponized, in former ­dictatorships and failed states throughout the Middle East.

“We were worried about this very dangerous material,” said Mohamed Taher Siyala, foreign minister of Libya’s unity government. If the Islamic State were to capture the chemicals, he said, “it would be dangerous not [just] for us but for the international community.”

The rush by the United States and its European allies to help Libya remove chemicals stored at the Ruwagha site, which had

been Gaddafi’s chemical-weapons farm, was also an indication of the Obama administration’s uneasiness about whether the shaky unity government would be able to secure materials that could be made into mustard gas.

“We placed a high degree of interest in moving these chemicals out of the country,” said a senior U.S. official, who like other officials spoke on the condition of anonymity to discuss the operation. “We had been focused on it since we learned it was there.”

The removal comes as U.S. warplanes continue daily strikes on Libya’s coastal city of Sirte, where a small group of Islamic State fighters has managed to hold off militia forces affiliated with the Western-backed government for months.

[Inside the brutal but bizarrely bureaucratic world of ISIS in Libya]

Recent progress to weaken the Islamic State, also known as ISIS, has not ended the prolonged political crisis that has spawned competing governments in Libya’s east and west and pushed the country to the brink of civil war. This week, a powerful eastern commander seized major oil ports, further inflaming tensions that have prevented the unity government — which the United States and its allies see as the sole path to stabilization — from consolidating its power.

According to a second U.S. official, links between the officials responsible for Ruwagha and the unity government were tenuous at best, adding to the sense of insecurity about the stockpile.

“Not to suggest that there was friction . . . but they didn’t have somebody that they would report to with clear distinction and chain of command,” the official said.

The material at Ruwagha, which included phosphorus trichloride and 2-chloroethanol, was the final remnant of a once-formidable chemical-weapons program built up by Gaddafi.

When Libya joined the Chemical Weapons Convention in 2004, the Gaddafi government declared a host of material it held in its chemical arsenal, including a vast store of bulk sulfur mustard agent. After Gaddafi’s ouster, the new government came across additional chemical weapons, mostly artillery and bombs filled with mustard gas, which were then reported to the Organization for the Prohibition of Chemical Weapons (OPCW), a global watchdog. By early 2014, all remaining weapons had been destroyed.

While some precursor materials were destroyed in 2015, nearly 500 tons of dual-use, toxic industrial chemicals remained at Ruwagha.

There was also an environmental hazard: The materials were stored in containers so corroded that chemicals were leaking into the soil.

Officials from the Libyan office responsible for chemical weapons had hoped to destroy the precursors domestically, using sophisticated plasma technology, but that proved impossible as a wave of kidnappings, insurgent attacks and militia clashes surged across the country.

Ali Gebril, who has been Libya’s representative to the OPCW since 2010, said officials’ fears about the remaining material increased in December 2015 when Islamic State fighters attacked a checkpoint about 45 miles from Ruwagha.

While U.S. and Libyan officials believed the Islamic State did not know about the presence of the chemicals, they feared that the site, which had also been used to store conventional weapons, might be targeted anyway. Already, Islamic State fighters were suspected of employing chemical weapons in Iraq and Syria; this week, U.S. warplanes destroyed a chemical-weapons factory in northern Iraq.

Their concern grew sharply when a second checkpoint was attacked in May, just over a mile from the facility. “We started really to think how to remove the chemicals from where they are,” Gebril said, or at least to move them from that vulnerable location.

In mid-July, the unity government renewed an earlier request to the OPCW, made more urgently this time, for help in removing the material. But securing international support to transport the chemicals would not be simple.

Under international rules, moving chemical-weapons material across international boundaries would require authorization from the United Nations. But officials worried that involving the world body might draw unwanted attention to the existence of the chemicals, including from the Islamic State.

Libyan officials also had a template as they made their request — the international collaboration to remove Syria’s chemicals weapons in 2014. “We told them it was an investment in world peace and security,” Gebril said. “We got huge support.”

Rebecca Hersman, a former Pentagon official overseeing chemical-weapons issues who is now at the Center for Strategic and International Studies, said the Libya operation, like the one in Syria, showed that such transport operations to remove chemicals could be cost-effective and safe, “rather than importing people and capabilities into that dangerous environment” to destroy them at the site.

In Washington, American officials received regular intelligence information and satellite imagery of the site. In mid-July, Libyan officials piled about 20 barrels — Canada had helped the government purchase new, safer containers — onto a small convoy of trucks and drove them across the desert to the coastal city of Misurata.

“Many people believed we couldn’t deliver and move the chemicals,” Gebril said.

At the same time, U.S. and European officials were scrambling to coordinate a way to get the chemicals out of Libya. On July 22, the U.N. Security Council voted to adopt a British-drafted resolution authorizing member countries to transport the material from Libya.

The White House decided it would not call attention to the unanimous vote until the materials had safely left Libya. “Everything we did we wanted to be just as low-profile as we possibly could,” the second U.S. official said.

In late August, the materials were loaded at the port of Misurata onto a Danish ship, which was accompanied across the Mediterranean by Danish and British naval ships. They were bound for the German city of Münster, where the chemicals will be destroyed in a commercial facility over six to nine months.

Although Libya remains perilously unstable, U.S. officials hope the operation can strengthen the unity government at a time when its future remains in doubt.

“The lesson learned is that the international community still really cares about making sure that we put threats like chemical weapons back in the box and we can come together in difficult circumstances to make that happen,” the first U.S. official said.

Amid the ongoing conflict, Gebril said the removal of deadly materials was one of the few things that Libya’s divided society could agree on. “It was in the interest of all Libyans to get these chemicals out of Libya and destroy them as soon as possible,” he said.

Read more:

Libyan force was a lesson in the limits of U.S. power

U.S. Special Operations troops aiding Libyan forces in battle against ISIS

Even with U.S. airstrikes, a struggle to oust ISIS from Libyan stronghold