In a set theory class I was taught composition of functions as a special case of composition of relations, and to think of dom $g\circ f$ as dom $f \cap f^{-1}[$dom $g]$.
Then when we speak of composition of two functions $f$ and $g$, do we allow both the cases that dom $g \subset$ im $f$ and im $f$ $\subset$ dom $g$?
In $(g \circ f)(x) = g(f(x))$, we input the output of $f$ into $g$. The domain of $g$ should be large enough to contain the range of $f$ so that this is well defined. (i.e. $\mathop{\rm im} f \subseteq \mathop{\rm dom} g$)
For a counterexample, take $g(y) = \sqrt{16 - y^2}$ so that $\mathop{\rm dom}g = [-4,4]$ (is small enough); and $f(x) = x$. If $|x|>4$ (is large enough), $g(f(x))$ is undefined.
picture from UCR Math Wiki
When we speak of $g \circ f$, we don't necessarily have $\mathop{\rm dom} g \subseteq \mathop{\rm im} f$, but you can restrict $\mathop{\rm dom} g$ so that they become equal.
For exampe, take $f: \Bbb R \to [-1,1]$ as $f(x) = \sin x$, and $g: \Bbb R \to \Bbb R$ as $g(x) = x$. $\mathop{\rm im} f = [-1,1]$ can't contain $\mathop{\rm dom} g = \Bbb R$.
Image from Wiki