Bug, an error or malfunction in a computer program or software, has been used to refer to defects or faults in machines since the 1870s. Most famously, the inventor Thomas Edison wrote in a letter dated 3rd March 1878, that he had found a bug in his apparatus. A popular anecdote about the computing pioneer Grace Hopper finding a moth inside the Mark II mainframe computer in 1947 is true but not the origin of the term.
Bug started life as bugge meaning a 'scarecrow or an object of fear' from the 15th century. Bugs didn’t become insects until the late 16th century, most commonly referring to bed-bugs, perhaps because waking up to bed-bug bites was like being visited by something scary during the night. Bugs didn't start cropping up in machinery until the the 1870s with the same connotation of something invisible or an object of fear or dread that was causing the issues.
One of earliest appearances of a mechanical bug was in The Operator, a journal for telegraph operators, that announced in 1875 that the biggest ‘bug’ yet had been discovered in the U.S Hotel Electric Annunciator, a mechanical device also known as a Butler’s Bell, that allowed hotel guests to contact reception if they wanted room service.
Source: Oxford English Dictionary.