In usual theories the number of freedom of a system can be obtained by looking at the number of variables in relation to the number of equations describing the system. In the case of classical electrodynamics one would be tempted to derive the equation of motion for the photon from the Lagrangian ${\scr{L}}=-\frac{1}{4}F_{\mu\nu}F^{\mu\nu}$ and try to constrain the 4 components of the $A_\mu$ field to two.
However, the $A_\mu$ field experiences gauge invariance $A_\mu \rightarrow A_\mu - \partial_\mu \alpha$. The values $\alpha$ can be choosen freely in the Lagrangian and this gauge invariance is responsible for a redundancy in the description of the system, the true number of degrees of freedom remains hidden. To find out the true physical degrees of freedom the system needs to be quantized and the gauge redundancy must be isolated. This is done through the Gupta-Bleuler formalism in the QED. The more general procedure is called Fadeev-Popov quantization and is also applicable to non-Abelian theories.
The main point in the quantization procedure is to write the photon field as a Fourier decomposition with annihilation and creation operators $a$ and $a^\dagger$:
$$A_\mu =\int \frac{d^4k}{(2\pi)^4}\sum_{\lambda=0}^3(e^{-ikx}a^\dagger(k)\epsilon_\mu(k, \lambda) + e^{ikx}a(k)\epsilon_\mu^*(k, \lambda)) .$$
The former four degrees of freedom of the system are now in the 4 linearly independent polarization vectors $\epsilon(k)$. The Lorentz gauge $\partial_\mu A^\mu =0$ must now be imposed on the quantum level, hence on the Hilbert space giving $k_\mu \epsilon^\mu= 0$. This is restricting the possible polarizations of the photon by eliminating the longitudinal polarizaiton. Hence, one degree of freedom is getting lost.
By continuing the procedure and using the massless condition $k^2=0$ one can make another possible polarization decouple from the physical degrees of freedom and leaving the system with only 2 pyhsical transverse polarizaions. The process of the quantization is higly non-trivial and so is the counting of degrees of freedom.