I understand what the idiom means: as per this question, it means a person or creature unwittingly used as a test for danger, often destructively.
I understand why coalmines: as depositories of ancient organic waste, they are particularly prone to methane and carbon monoxide buildup.
But why a canary? They are technically exotic, native and (at least originally) endemic to the sub-tropical Canary Islands, which gave them their name. They were also renowned for their singing voice, as found out in this answer, and could presumably be quite expensive.
So why would a mining company in Britain and/or America and/or any other English speaking country use such an expensive and exotic bird as a glorified carbon monoxide detector whose sole purpose in life was to suffocate to death? Why wouldn’t they use sparrows, or starlings, or some other small songbird native to the area? Are canaries just that easy to breed and keep? Are they super-extra-sensitive to poison gases and thus were the “upscale” model? Were all small, caged songbirds called “canaries” as a matter of course?
Or did the modern idiom simply opt for alliteration over historical accuracy?
Canaries were not only used in coal mines. The old Normanby Park steelworks in Scunthorpe had an aviary as late as the mid twentieth century where they bred canaries for gas detection purposes. They were so good at breeding that they showed the best looking birds (and probably the best singers) in competition with other breeders.
A caged canary would be taken in into an area where CO and other dangerous gases might be present; if there was a concentration of dangerous gas the bird would pass out and fall off its perch but would usually recover quickly after it was removed from danger.
Because they are quite easy to breed in captivity canaries, although an introduced species, have been quite cheap to buy and keep in the UK. Before the introduction of canaries as pets caged linnets were often kept for their song, but I believe that they were captured from the wild rather than bred. Interestingly country people who couldn’t afford parrots (which were and are expensive) would sometimes keep captured jays or jackdaws as pets for their mimic abilities.