The story
Sense 2 (“to behave in a manner on the verge of being dangerous, illegal, or improper”) derives from the fact that to sail an old-fashioned sailing ship close to the direction the wind was blowing from was risky because a small change in the wind direction could fill the sails and push them against the mast, potentially breaking it.
Etymology from Wiktionary, CC BY-SA 4.0.