It must be flush or slightly deeper than the outside of the drywall. No gap between the box and drywall. If you have a gap, you can get an extension ring. This will allow you to adjust the depth as needed.
Most boxes are recessed into the drywall as to allow for the device and plate to be perfectly flush with the wall.