A few different origins, but the most popular being to do with the use of cannons. Somebody would light the cannon with a flaming stick when they lit the cannon they would have a couple of seconds to say fire in the hole so anyone behind the cannon could get out of the way of the recoil.