Because they have a limit switch on the door, which does this automatically when enabled. It's manually set by crew as part of dog-zebra procedure, or relay-controlled from the bridge.
The underlying purpose is to darken the ship to avoid sighting by the submarine at night. This is done in a ship's state known as Dog Zebra material condition in the US Navy, and other navies have similar procedures, as do merchant marines, for the same reason.
In movies/TV, the most well-known example of material conditions is the "Set Condition One throughout the ship" callout, used in in Battlestar Galactica 2004 and Star Trek: Deep Space Nine (on Klingon vessels), both Ronald D. Moore joints.
If you're wondering... X-ray, Yoke and Zebra are elevating levels of securing internal hatches and valves to improve watertightness. "Dog" is an amendment to "Zebra" that means "also do not emit light".