One of the oldest questions for mankind is how the Earth was formed. However, no one has an exact answer. First by the best estimates it occurred over 4 billion years ago before any life appeared. So there are no eyewitness accounts and other pieces of evidence. The best we can do is look at the geologic record and the stars to get our answers. While we may not have the entire picture we have a good idea and it all starts with how stars are born.
Just like the formation of the Earth and other planets stars take a long time to be be born. Stars are essentially formed from clouds of gas in space. We know these as nebulas. You can basically consider them to be star forges. Over time gravity causes the atoms of gases and space dust to start coming together and gathering. Over time this gather of gases gains more mass and with it stronger gravity. This is a process that can take millions of years. In time the gravity causes the gases, mainly hydrogen to fuse in a nuclear reaction and a star is formed.
The formation of the Earth occurred after this intial phase happened for our Sun. After the Sun was formed we know from observations and other indirect evidence that there were left over gases and heavier elements. The gravity of the Sun helped to flatten these left overs into a disk and start to fuse them together. This created the planetesimals and planetoids which would later make up the planets. Over time these planetesimals would collide creating even bigger masses. It was in this method that the Earth was eventually formed.
Now we need to know that fusion eventually creates heavier elements such as carbon and iron. These elements were to compose a significant part of young Earth. The pressure and heat from radioactive decay of elements and the aftershocks of massive collisions caused the Earth to be molten. Over time the surface of the Earth cooled and became the Crust. However the molten layers that remained became our mantle and the core. The currents of this massive underground ocean of magma cause volcanic activity that released gases. These would lead to the creation of the atmosphere and the oceans starting the water cycle.
The formation of the Earth was only the beginning and we still see the Earth changing year by years through erosion and plate tectonics. However in learning more about the formation of the Earth we are able to better understand what makes life possible on our planet.
You can also find some great resources online. There is a great web page on the University of Oregon web site that goes into detail about the formation of the Earth. You can also look at the Hadean page on the Smithsonian website. It talks about the Hadean period the period of geologic time when the Earth was formed.
You can also listen to Astronomy Cast. Episode 108 is about the life of the Sun.