4.6BYA the Earth's atmosphere was almost non existent. As the Earth cooled, an atmosphere formed with a composition of mostly methane and carbon dioxide with some ammonia.
Next came the Archean Eon. There was no oxygen gas on Earth. Around 2.7BYA blue-green microorganisms called cyanobacteria appeared in Earth's oceans. They produced gaseous Oxygen through photosynthesis and solar energy.
Eventually enough Oxygen was produced to form a chemical reaction with iron to form rust.
As oxygen became more and more abundant, its presence benefited aerobic life but it didn't benefit anaerobic life as anaerobic life had no need for Oxygen.
Eventually around 350MYA the Earth's atmosphere evolved into what we know today. Oxygen was much more abundant and hydrogen and ozone became present. Earth's atmosphere doesn't float off into space thanks to the Earth's gravity.
Thanks to ozone in the Earth's atmosphere the Earth is shielded from harmful ultraviolet radiation from the sun.