Merriam-Webster dates the first usage of red flag meaning "a warning signal" to 1748, but it does not cite the example. However, the Collins Dictionary Trends of 'red flag' graph lends support to this early usage
Still well before railways, the earliest actual example of the use of red for a warning I've found is in this Wikipedia note:
1777 Philip Thicknesse, Year's Journey I. iii. 23 There is a red flag
hoisted gradually higher and higher, as the water flows into the
harbour [at Calais].
Early Western Travels 1748-1846 has this passage from 1812-1819, a possible reference to warning or danger:
Several times hearing the noise of cannon, and seeing a red flag
hoisted, on inquiry I found that one or more negroes were to be
The Army and Navy Chronicle, volume VI has this use (1837) of a red flag to warn against fog at sea:
In rainy and foggy weather, this vessel's bell will be rung for 10
minutes at a time, after intervals of 5 minutes duration. During the
day time a red flag will be kept flying at the foretop, and in stormy
weather a red jack will be hoisted at the same top.
Red did not actually become the standard warning colour on railways until 1841 or a little later, partly at the urging of Henry Booth of the Liverpool and Manchester Railway when his views were sought by the House of Lords Select Committee on Railways. The gas lamps sometimes used (with red or green glass) were soon phased out in favour of semaphore signals.
Perhaps the most notable use of red meaning 'warning' or 'danger' does, though, relate to railways (and other 'self-propelled vehicles') in the form of the The Locomotive Act 1865, also known as the Red Flag Act which stipulated that
self-propelled vehicles should be accompanied by a crew of three; if
the vehicle was attached to two or more vehicles an additional person
was to accompany the vehicles; a man with a red flag was to walk at
least 60 yd (55 m) ahead of each vehicle, who was also required to
assist with the passage of horses and carriages. The vehicle was
required to stop at the signal of the flagbearer. (Section 3)
Red flags were also used by ships of the Royal Navy from at least 1602 to indicate that they were going to engage the enemy. A specific example is cited here in The Navy Chronicle. Also, pirates of the late 17th and early 18th centuries
actually bore no designs, but
were flags of solid red or black. The origin of the red flag can be
traced back to the English privateers of the late 1600s, who were
required to fly red flags to distinguish their vessels from those of
the Royal Navy. Many of these privateers later turned to piracy, and
continued to use the red flag.