To open och close your gates go to your Rally Spot in the town and mark or unmark the form in question.
If the gates will be open your army inside the city will defend against an attack together with your town defense (archery towers, rollinglogs etc). If your gates are closed the army wont take part in the battle.
My suggestion is to keep your gates closed: most of the attacks on your town will be for plunder, not actual city takeover. If you let your army out they will probably be defeated and after the plunder you will have no defense what so ever. Neither will you have any army to gather your own plunder to rebuild your towers and other defenses. With out an army you will be paralized for days.