The earliest airplanes copied the designs of the 1903 Wright Flyer, on which the pilot lay on the wing, in the open and subject to the wind.
As airplanes developed over the next five years years, constructors like France’s Louis Blériot built an enclosed a space to protect the pilot from the wind and cold.
This space had a slight resemblance to a cockpit, the small round enclosure in which two fighting cocks were thrown.
The term was already used in sailing vessels (see Cody Kent‘s comment), and was in widespread use in aviation by 1913. From aviation, it seems to have spread to sailboating and to auto racing.