How was water formed? We know that a planet is formed from the nebula of gas and dust. Gravity pulls the particles together in a core. So we all know that the gas cloud is a cloud of hydrogen.  

But how did water form? From where did oxygen come? How did it combine to make $\text{H}_2\text{O}$?
Stars, especially larger stars, are hot enough at their core to produce significant amounts of heavier elements: Carbon, Nitrogen and Oxygen. When the stars die, some of these elements are returned to the interstellar medium. 

The nebula from which stars form contains not only Hydrogen, but also all the other elements found on Earth. The nebula contains the Carbon that is the basis of life, the Nitrogen that forms the atmosphere, the Silicon that makes rocks, and the oxygen that reacts with hydrogen to form water. 

Most of the water on Earth was actually brought to the Earth on asteroids after the Earth had formed, see How did water get on Earth