You have several ways to go about it.
First, a set of powerful nations will recognise and guarantee the independence up to going to war over the state. This is generally the peaceful way as everyone comes to an agreement that this is what should happen. Some countries (such as Poland) were re-made after a war and given independence again. India could be said to be in this camp as it peacefully split from the British Empire.
Second, a country declares itself independent and forces the rest of the world to recognise them. This is what happened to the confederate states in the USA civil war... Or rather that is what they tried and failed to do. This is more risky since the rebels have clearly some difficulties in being legitimate.
Lastly, a country can force independence and not be recognised by anyone or just a few nations. They become a rather odd entity -- as was Afghanistan under the Taliban was one such nation even though it was a country its government was not recognised by the vaste majority of countries . I am unsure of their legal status but if the country does not have friends, they are doomed.
There are many international agreements and codes but there is no supreme court of law of the world. So, the legality of becoming independent is murky at best. Even international law is by agreement of countries. It is up to the club of nations signing the treaty to defend it. If they do not, then it's just ink on a page.