The flame's heat kicks a metal ion's outer electron up to a higher, unstable energy level. When it drops back down, it releases the exact energy gap as a photon of one specific wavelength — the ion's spectral "fingerprint". Different metals have different electron shell spacings, so each burns a different color.
Li crimson-red (670.8 nm), Na intense yellow (589 nm sodium D-line), K lilac (mix of 404 and 766-770 nm, best seen through blue cobalt glass that filters the sodium contamination), Cu blue-green (mostly molecular CuCl emission near 535 nm), Ca orange-red (~622 nm CaCl/CaOH band), Sr crimson-red (~605-682 nm, brighter than Li), Ba apple-green (~524 nm BaOH band).
This is the same physics that colors fireworks and lets astronomers read the composition of distant stars from their spectral lines.