RIO DE JANEIRO — A judge in Brazil ruled on Sunday that former President Luiz Inácio Lula da Silva be released from prison while he continues to appeal a corruption conviction, an unexpected decision that touched off an immediate legal and political uproar.

The order was the latest twist in the tumultuous lead-up to Brazil’s presidential election in October. Even from prison, Mr. da Silva holds a lead in the polls. He is hoping to be on the ballot even though the corruption conviction for which he is serving a 12-year sentence makes him legally ineligible to run for office.

Yet as uncertainty about Mr. da Silva’s fate ignited a fierce debate among Brazilians, Judge João Pedro Gebran Neto, the chief appellate judge overseeing the case, overruled the order authorizing the release and instructed the police to keep the former president in custody.

The saga began early Sunday when a federal judge, Rogério Favreto, who has ties to Mr. da Silva’s leftist Workers’ Party, ordered the former president’s release.