BANGKOK — A Thai soldier armed with military firearms rampaged through a bustling shopping mall and an army camp, killing 29 people before he himself was killed after a 17-hour standoff with security forces, Thai officials said, in a rare mass shooting that has shaken the country.

After live-streaming part of the shooting on Facebook, the gunman holed up in the mall with several hostages, as police secured the area in the early-morning darkness. The sound of gunfire emanated from the building before 3 a.m., and ambulances rushed in and out of the mall compound, according to live broadcasts from the scene. Mall workers and shoppers crawled out from fire exits and glass entrances, staying low to avoid bullets, escaping in small groups throughout the morning.

The standoff finally ended when security forces killed the shooter at 9 a.m. on Sunday. He injured 58 people, Thai officials said, 25 of whom had been discharged by noon Sunday. Eight hostages were rescued when he was killed, and some were among the injured, officials added.

"We feel sorry for the affected families and their losses," said Lt. Gen. Thanya Kriatisarn, commander of the Second Army Region.

Authorities identified the alleged shooter, who carried an assault rifle and was clad in camouflage and a helmet, as 32-year-old Jakrapanth Thomma, a sergeant in the Thai military.

The attack is at least the second mall shooting in Thailand this year. On Jan. 9, a masked gunman fatally shot three people, including a 2-year-old boy, while he robbed a jewelry store in the city of Lopburi. A suspect was arrested, reportedly confessed and said that he had not meant to shoot anyone.

Saturday’s violence began around 3:30 p.m., when police say the gunman fatally shot his commanding officer, took several military firearms and drove about nine miles in a stolen Humvee to the Terminal 21 mall in Nakhon Ratchasima. He also killed a 63-year old woman at the army camp, and another soldier who was a guard at the weapons storage facility.

The alleged shooter was under Thailand’s 23rd infantry regiment, which oversees Surathampitak camp.

“He pointed a gun at a soldier in the camp and stole firearms from him,” Prayut Chan-ocha, Thailand’s prime minister, said at a news conference on Sunday. “Then, he used that stolen weapon to kill another guard at the ammunition storage area.”

Nakhon Ratchasima, also known as Korat, is about 3 1 / 2 hours by car from Bangkok.

Arriving at the Terminal 21 mall, he fired at shoppers and drivers on the packed roadways. He entered the building — a seven-story complex with floors modeled after cities like Paris and Tokyo — with several firearms, including an automatic rifle.

As the standoff dragged on at the shopping mall, security surrounded the building, sealing off surrounding roads. Police also retrieved the shooter’s mother from neighboring Chaiyaphum province, about 60 miles away, and used her to negotiate with the suspect.

Authorities have so far struggled to find a motive for the killings. Prayut, at the news conference, said the gunman could have been dealing with personal issues over money and a land purchase gone wrong.

“We need to look at his mental health,” the prime minister said. “Everyone has problems.”

The Bangkok Post identified the deceased commanding officer as Col. Anantharot Krasae, 48, with whom the alleged gunman reportedly had a conflict.

On Saturday, a witness told The Washington Post she was inside the dental office where she works at the mall when she heard gunshots and saw people running. Employees locked the door, turned off the lights and shut down the air conditioning. Eventually, a security guard told them to leave, the 36-year-old woman said, so they fled through the fire exit and crawled on the ground to avoid gunfire.

“The police just told us to run, and run away as fast as we could,” said the woman, who identified herself only by her first name, Yannapat.

She said that the streets surrounding the mall were closed off and that police asked bystanders to stay at least a mile from the scene.

Nattaya Nganiem shot a video from outside the mall and said she and her family had left just before the gunfire began.

“We couldn’t see the gunman, but we could hear the sound of the gun. It was terrifying,” Nattaya told the AP. “I can’t believe this is happening in my hometown. I mean, this shopping mall, we go there almost every other day.”

Mass shootings in Thailand like Saturday’s are extremely unusual, especially outside parts of the south where a Muslim insurgency is fighting against the majority Buddhist state. The right to private gun ownership is not guaranteed in the country, but firearm smuggling rates are high, and the black market is thriving, according to the University of Sydney School of Public Health’s international gun policy site.

The alleged gunman periodically posted videos and photos to Facebook during the rampage. “No one can escape death,” he wrote, and he asked whether he should “give up.”

At one point, he wrote that he was “very tired.”

“I can’t even move my finger anymore,” he said, likely in reference to his trigger finger. Facebook suspended the gunman’s account soon after the videos began to circulate.

Cellphone video published by the Thai Rath network shows the suspected gunman emerging from behind a vehicle to shoot at a motorcyclist, who appears to be struck as he flees. The man can also be seen firing volleys down the street outside the mall as bystanders sprint to safety and take cover amid abandoned cars.

Surveillance video from inside the mall showed the suspected gunman, his face obscured by a balaclava, toting a rifle on his shoulder as he strolled across the shopping center’s white marble floor.

Other photos and video on the Thai Rath broadcast show the purported gunman in selfies holding a variety of firearms and wearing digital camouflage issued to the military. In one photo taken outside, he poses with a fire raging behind him.

The gunman’s self-conscious effort to spread violent imagery on social media as the killings unfolded echoes the 2019 massacre in Christchurch, New Zealand, where a gunman used Facebook to live-stream his attack on two mosques. And as in that incident, video and photos taken by the gunman rocketed across message boards such as 4chan.

It was unclear how many or what kinds of firearms the gunman took from the camp, though he posed in selfies on social media with a variant of the HK G3 rifle, used by the Thai military, along with a pistol.

Although controlled semiautomatic fire is heard in several videos recorded during the incident, one video taken from a gym near the mall briefly captured sounds that could have been automatic fire. Many military rifles have a selector switch to regulate ­between semiautomatic — which fires one bullet with every trigger pull — and automatic fire, which fires bullets at a high rate while the trigger is held.

It is relatively easy to legally obtain a gun in Thailand. Beyond military use, a prospective gun owner needs to show a valid reason for owning a gun, such as hunting or self-defense. The minimum age to own a gun in Thailand is 20, and the owner must pass a criminal-background check.

The annual rate of gun deaths in 2016 in Thailand was 2.54 per 100,000 people, according to the University of Sydney’s School of Public Health. The rate in the United States was 11.96 deaths per 100,000 people in the same year. Over the past several years, the total number of gun deaths in Thailand has decreased from 3,420 in 2007 to 1,729 in 2016.

An earlier version of this article misstated the number of people reported dead in the attack. Thai authorities say 29 people were killed or mortally wounded by the alleged gunman before he was himself killed, leaving a total of 30 dead.

Mahtani reported from Yangon, Myanmar. Horton, Mettler and Iati reported from Washington.