To understand how earthquake occurs, we have to start with the interior structure of the Earth. Shaking of the ground during an earthquake is caused by the passage of a seismic wave, similar to the ripples on the water surface when a rock drops into a still pond. But what trickers the seismic wave?
The Earth is not a uniform solid ball, but instead made of mainly three different layers according to the composition, these are:
1, the core, which comprises of the inner core made of solid nickel and iron due to high pressure, T = 5500 to 7000 oC, and the outer core made of liquid molten nickel and iron, T = 6100 to 4400 oC;
2, the mantle, which is made of silicate rocks rich in magnesium and iron. It is separated into the lower mantle (hot, semi-solid rock with the consistency of hot asphalt), and the upper mantle (bottom portion is semi-solid or ‘plastic’ and top portion is solid);
3, the crust, which is the solid surface layer of the Earth (the oceanic crust is made mostly of dense basalt, and the continental crust is made mostly of less dense granite).
However, if we instead focus on the mechanical behaviour, the crust and the top portion of the upper mantle are rigid and move around together. They are referred to as the lithosphere (from Greek: lithos for “rocky”, and sphaira for “sphere”). Just below the lithosphere is the asthenosphere (from Greek asthenḗs for “weak” and “sphere”), which is the highly viscous, mechanically weak and ductilely deforming region of the upper mantle. One can think of the hard lithosphere being “floating” on the soft asthenosphere. The only issue is that the lithosphere is not one continuous layer, but instead breaks apart into pieces matching together like a giant jigsaw puzzle. Each piece is called a tectonic plate as shown in the figure below.
Public Domain, https://commons.wikimedia.org/w/index.php?curid=61568
When these tectonic plates “float” on the soft, ductile asthenosphere, they moves apart from each other, joint together or pass by each other. In these cases, the boundaries are referred to as divergent, convergent and transform boundaries, respectively. At the boundaries is where earthquake tends to occur. Take a transform boundary as an example, keep in mind that the edge of each plate is not smooth, so friction occurs at the boundary. While the plates continue to move passing by each other, tension build at the boundary until they eventual unstick and shockwave is generated.
You can find more details about this process in this fantastic Youtube video.