This is related to the so-called "colour charge" carried by particles involved in strong interaction. Although at first it was proposed to allow same quarks exist inside the baryons (despite Pauli exclusion principle), it is also used to describe the ability of hadrons to be free of confinement — only colourless particles (or white) can be free.
This is not a full-blown explanation of the phenomenon — it is rather a model that describes well all the variety of known hadrons based on their symmetry. As fas as I know, the problem of implementation of confinement itself remains difficult.
There are 3 colours (red, green, blue) and the associated anticolours. For example, meson contain pairs of colour-anticolour quarks while baryons contain 3 different colours that together also are colourless.
See more here: https://www.wikiwand.com/en/Color_charge
Regarding the second part of the question. Basically, yes, nucleons and mesons are stable entities with respect to QCD. Nuclei are well described as conglomerations of nucleons with small discrepancies. At the same time, mesons for a long time are considered the carriers of the strong interaction — not unlike photons in QED.
However, this "stability" is possible only below the QCD crossover energy scale when hadrons deconfine and form a quark-qluon plasma. In some sense, one may consider an analogy to atoms that are themselves electrically neutral (but consist of charged particles) and are being dissociated at high temperatures.