Loose Cannon

I know the (current) meaning. Where did this phrase originate?

On battleships, I believe, where a cannon rolling around on the deck could cause lots of damage. I can't remember where I read that.