Let's build a fortress to see the different defences at work.
First we build a keep, It's a big fortified tower or house. This is the last line of defence and where the object of defence is kept, wether it's a noble family, a treasure, the villagers or just the place itself. The perfect location is on ha hill, it's always much more difficult attacking uphill. In the early middle ages they often build the hills themselves, these are called mottes.
To add a layer of defence we add a wall outside the keep. It could go around it or be attached to the back wall of the keep. The area enclosed are called a courtyard or a baily. We now have a good defense from the early middle ages called a motte-and-baily.
We do have one big gaping hole in our defense, the entrance must be a hole in the wall. A wall with a hole is an invitation for attack, even with a big heavy door, it's the most voulnerable spot. So we thicken the wall around the gate to twice the thickness of the walls and put a tower on top. Now we have a gatehouse. The tunnel that runs through it can be gated at both ends, filled with logs and debris and from the second floor, holes in roof of the tunnel (aptly called murderholes) can be used to tip boiling water, flammable oil or stones and arrows onto the packed assault force. The gate is secured.