How can we derive the gauge field Lagrangian? I learned the gauge field Lagrangian is given in this form: 
$$\mathcal{L} = -\frac{1}{4} \mathrm{Tr}(F_{\mu \nu}F^{\mu \nu}).$$


*

*But how one can derive this equation starting from defining the covariant derivative
$$D_{\mu} = \partial_{\mu} - igA_\mu ~?$$

*And is this Lagrangian certainly invariant under the gauge transformation?
 A: The Lagrangian must be a gauge invariant and Lorentz invariant object that can be integrated over the entire spacetime $\Sigma$.
So, we must first obtain an $n$-form (for $n$ the dimension of spacetime), and all that we have for that is the gauge field $A$, which itself transforms in an ugly way under gauge transformation. The only object we can build out of it is its own covariant derivative $\mathrm{d}_A A$, where $\mathrm{d}_A \omega = \mathrm{d} \omega + A \wedge \omega$ for arbitrary forms. (In coordinates, this is indeed $D_\mu = \partial_\mu - \mathrm{i}g A_\mu$ on 1-forms if we restore the factors of $g$ and $\mathrm{i}$ physicists seem to love so much). One can check that
$$ \mathrm{d}_A A = [\mathrm{d}_A,\mathrm{d}_A]$$
so that both $\mathrm{d}_A A$ and $[D_\mu,D_\nu]$ are equivalent definitions of the field strength $F_{\mu\nu}$. By direct computation, it is shown that the field strength transforms in the adjoint representation of the gauge group, i.e. for a gauge transformation $t : \Sigma \to G$ it transforms as
$$ F \mapsto t^{-1}Ft$$
Now, $F$ is a $2$-form (since it is the derivative of the $1$-form $A$). How do we, in an arbitrary setting, make a $n$-form out of it? Answer: Provided that there's a metric on spacetime, we take the Hodge dual $\star F$, which is a $n - 2$-form, of it and wedge them together as $F \wedge \star F$. As an $n$-form, it is a pseudoscalar form and thus (proper) Lorentz invariant. Furthermore, it still transforms in the adjoint by linearity of the wedge and Hodge star:
$$ F \wedge \star F \mapsto (t^{-1}Ft) \wedge \star(t^{-1}Ft) = t^{-1}F \wedge \star F t = t^{-1}(F\wedge\star F)t$$
and by cyclicity of the trace ($\mathrm{Tr}(A_1\dots A_n) = \mathrm{Tr}(A_n A_1 \dots A_{n-1})$), its trace does not transform at all. Therefore, $\mathrm{Tr}(F \wedge \star F)$ is a Lorentz and gauge invariant $n$-form, and thus a viable summand in the Lagrangian. In the general setting, there is no other such $n$-form constructed only out of the gauge field, so the Yang-Mills Lagrangian is the only action we can write down for only the gauge field in arbitrary dimension.
Note that, in the usual 4D setting, there is prominently the second Chern class $\mathrm{Tr}(F\wedge F)$ as a second invariant term, but whose integral is a topological invariant and describes the instanton number.
