Millions of years ago, dense forests got buried under the soil due to natural processes like storms, floods, and earthquakes. These got compressed as more and more soil got deposited over them. When they got buried deep in the soil, they were exposed to very high pressure and temperature.
Under these conditions, these slowly got converted into coal. This process of the formation of coal from dead vegetation is called carbonization.