In relativistic physics there is no conservation of mass, and if I write mass I always mean what's called "invariant mass" not "relativistic mass", which is a misnomer for the energy of the system divided by ##c^2##, but only energy and momentum conservation.
If you have some protons and neutrons at rest, the total energy is ##E_0=(Z m_p+(A-Z) m_n)c^2##, where ##Z## is the number of protons and ##(A-Z)## the number of neutrons (##A## is called the number of nucleons). Now when these nucleons bind together to a nucleus, there is some binding energy, ##-E_B##, which is negative, and it's freed somehow, e.g., by electromagnetic radiation. So the energy of the nucleus at rest is
$$E_A=E_0-E_B$$,
but by definition for the nuclus at rest you have the invariant mass of the nucleus
$$m_A=E_A/c^2.$$
in other words the mass of the nucleus is smaller than the sum of the masses of the nucleons by the amount ##E_B/c^2##.
The same holds true for any other system too. E.g., suppose you have a capacitor with capacitance ##C## and let it's mass be ##m_0## if it's uncharged. Now if you charge it by connecting it to a battery of voltage ##U## the electromagnetic energy stored in this capacitor is
$$E_{\text{em}}=\frac{C}{2}U^2,$$
and this amount of energy you must provide from the battery. Consequently the mass of the charged capacitor is a bit larger than when it's uncharged, i.e., you have
$$m_{\text{charged}}=m_0+\frac{C}{2c^2} U^2.$$
The case of nucleons as bound states of quarks is much more involved and not fully understood. The reason is that the strong interaction is confining, i.e., we never observe free quarks and gluons but only color-charge neutral objects, the hadrons (baryons as bound states of three quarks and mesons as bound states of a quark and an anti-quark). The bound state is a very complicated system of bound quarks and gluons, and about 98% of the proton mass comes somehow from the dynamics of the quark- and gluon-quantum fields. As I said, it's not fully understood, but we have very convincing reasons to believe in this picture, because there are socalled lattice-QCD calculations of the hadron-mass spectrum. The idea behind this is to model space and time as a discrete lattice of points and evaluate the socalled Euclidean path integral of QCD approximately on big computers. With this you can evaluate the masses of the hadrons from QCD. The socalled current-quark mass of u- and d-quarks is only some ##\mathrm{MeV}/c^2## (which is due to the famous Higgs mechanism of the electroweak theory), but nevertheless the mass of the proton comes out at the observed physical value of about ##940 \text{MeV}/c^2##. So it must be the dynamics of the quantum fields via the strong interaction that generates almost the entire mass of the nucleon.