Sites produce duplicates without meaning to: with and without www, with and without a trailing slash, with tracking parameters. The canonical tag resolves them to one address so ranking signals are not split.
It has to agree with everything else. If the canonical says the apex domain but the site redirects to www, Google sees a contradiction and can refuse to index either. This site once lost a week of indexing to exactly that mismatch, which is why it is now checked in the build.
Every page should carry one, pointing at itself, on the domain the site actually serves.