A magnetic compass works because its needle is a small magnet that can pivot freely. Earth’s magnetic field exerts a twisting force (torque) on the needle, so it lines up with the horizontal part of that field, with its north end pointing roughly toward Earth’s north magnetic pole. That means a compass shows magnetic north, not true (geographic) north. The angle between the two, called magnetic declination, changes from place to place, which is why maps list the local declination and some compasses let you adjust for it. Nearby iron, steel, or electric currents create their own magnetic fields and can pull the needle off, so readings are most reliable away from metal objects and electronics.
Source: Compass — Wikipedia
Image: Lensatic compass with sighting, photo by Jacek Halicki (CC BY-SA 4.0), via Wikimedia Commons.