There are two ways to defend, either with your castle walls and fortifications or with your army.
Defending with your walls is the default. This allows you to keep your army safe and sound inside the city while you're offline, but will not prevent enemy scouting. If a very strong force is sent they may get through your walls. In this case, your army will be the second line of defense but may still be overrun.
To defend with your army as the first line of defense, go to the Rally Spot and select the checkbox to Open the Gates. This allows your army to run out of the gate and attack as soon as your Beacon Tower spots an approaching army. This works especially well to prevent enemy scouting of your city as the same will happen, your scouts will go to eliminate the enemy's before they find anything out. If an attack comes while you're offline, you may lose your army if the offending force is much bigger. Your walls will then be backup for whatever your army didn't manage to kill before they were slaughtered.