If $f:X\to Y$ is an epimorphism, define $g_1:Y\to\{0,1\}$ with $g_1(y)=0$ for all $y\in Y$, and $$g_2(y)=\begin{cases}0&y\in\mathrm{im}(f)\\1&\text{otherwise}\end{cases}$$
Then for $x\in X$ we see that $g_1\circ f (x)=0= g_2\circ f(x)$. From the property of epimorphism, this means that $g_1=g_2$, which is only possible if $\mathrm{im}(f)$ is all of $Y$.
Now, if $f$ is surjective, then take $g_1,g_2:Y\to Z$ with $g_1\circ f = g_2\circ f$. Then for any $y\in Y$, we can find $x\in X$ such that $f(x)=y$. Then $$g_1(y)=g_1\circ f (x)=g_2\circ f(x)=g_2(y)$$
So $g_1=g_2$.
As Qiaochu notes, kernels and cokernels don't make sense in an arbitrary category: you need a zero object to even define what these should be (and even with a zero object, they aren't guaranteed to exist).
If you have a category with a zero object, then a monomorphism $f$ has zero kernel: $f\circ\ker f = 0 = f\circ 0\implies \ker f = 0$. This doesn't show that the kernel actually exists, just that if it does, it must be equal to zero. However, it is not difficult to verify that $0$ satisfies the universal property of the kernel in this case. Reverse all the arrows to get the dual statement for cokernels.
However, the converse is false: consider the category with four objects $A$, $B$, $C$, and a zero object $0$ and morphisms
\begin{align*}
\operatorname{Hom}(X,X) &= \{0, id_X\}\quad\textrm{for each object }X\\
\operatorname{Hom}(B,C) &= \{0, f\}\\
\operatorname{Hom}(A,B) &= \{0,g,h\}\\
\operatorname{Hom}(A,C) &= \{0, fg = fh\}\\
\operatorname{Hom}(C,A) &= \operatorname{Hom}(C,B) = \operatorname{Hom}(B,A) =\{0\}.
\end{align*}
By construction, $g\neq h$, $fg = fh$, and you can verify that $\ker f$ exists and is equal to $0 : 0\to X$.
Best Answer
In general there is no reason for this to be true. A simple counterexample is the category with one object $x$ and exactly one non-identity arrow $f:x\to x$, where $f\circ f=f$. In this category $f$ is neither a monomorphism nor an epimorphism, so the only monomorphism/epimorphism is the identity, and $f$ is not a composition of the identity with itself. More generally, if $\mathcal{C}$ is a category where every epimorphism or monomorphism is an isomorphism, then clearly an arrow that is not an isomorphism cannot be decomposed like that (though I can't think of any other example of this kind).
It is true, however, for most concrete categories that one usually considers; in particular, a category where every morphism factors as a strong epimorphism followed by a monomorphism and strong epimorphisms are stable under pullbacks is called a regular category, and any quasivariety of universal algebra, any abelian category or any quasitopos is regular. Note that the category of topological spaces is not regular, but it still has the property that every arrow factors as an epi followed by a mono (in fact its dual is regular).