Magma forms when rocks in the mantle melt due to changes in pressure or the addition of water. Although temperatures in the earth's mantle are much hotter than melting temperature, there is not a layer of magma or molten rock under the earth's surface at any given time because there is too much pressure for rock to melt. Rather, magma forms here and there because of certain changes.
According to How Stuff Works, magma exists in solid, liquid and gaseous states simultaneously. Magma typically occurs along tectonic plate boundaries because of the way these plates interact with each other. If plates move away from each other, the pressure in the mantle changes, because suddenly there is a void for the rock to fill. This change in pressure starts melting the mantle rock into magma. Magma also forms when two plates collide. This collision forms a trench where once more pressure in the mantle changes. If it occurs in the ocean, water lowers the melting point of the rocks. In both instances magma once more forms.
According to Volcano World, occasionally the magma will be contained within a magma chamber, usually beneath a volcano. This magma is released when gas from the magma exerts a great enough pressure.