Heraldic devices, such as coat-of-arms and flags, evolved from a time when the instant recognition of such a device was imperative. If you could not distinguish the difference between the heraldry of your friend and that of your foe (through a small horizontal slit in your helmet during a pitched battle), then you might end up thrusting your sword into the wrong body, and have both sides of the battlefield against you. Inconvenient, to say the least.
So heraldic rules evolved from days of yore, to ensure that flags and arms could be easily recognised, and indeed, differentiated from one another. Although coats-of-arms seemed to have taken a detour in the past few centuries, national flags have stayed true to this.
There are 5 Colours in (English) heraldry — Black, Blue, Red, Green and Purple — and 2 Metals — White (or Silver) and Yellow (or Gold). Purple does not appear in any country's flag, however Orange and Light Blue turn up.

Bhutan

Tuvalu
Heraldic rules basically aim to avoid, as much as possible, two Colours (or two Metals) touching. Hence in New Zealand's flag, it has Red stars on a Blue background, but the stars are surrounded (or "fimbriated") by White — and so obeys these rules. Of course some of the newer flags of the world show no regard for these rules, as in Malawi.

New Zealand

Malawi
Red, White & Blue is the most popular colour combination (no surprise there).

Mauritania

Jamaica

Kazakhstan

Palau

Sweden

Bahamas

Ukraine

Congo
(formally Zaire)

Barbados

Bosnia

Nauru

St Lucia

Gabon

St Vincent & the Grenadines

Tanzania

Brazil

Solomon Islands

Lesotho

Sierra Leone

Djibouti

Uzbekistan