The short answer is: banks are less concerned about the interest earned on any single mortgage than they are for the interest earned over time from a collection of mortgages.
Let's look at a repayment schedule for a 30-year mortgage at 4% for $100,000.
Principal Interest Balance
Year 1 $1,761.09 $3,967.95 $98,238.91
Year 2 $1,832.85 $3,896.19 $96,406.06
Year 3 $1,907.52 $3,821.52 $94,498.54
Year 4 $1,985.22 $3,743.82 $92,513.32
Year 5 $2,066.11 $3,662.93 $90,447.21
Year 6 $2,150.30 $3,578.74 $88,296.91
Year 7 $2,237.89 $3,491.15 $86,059.02
Year 8 $2,329.07 $3,399.97 $83,729.95
Year 9 $2,423.95 $3,305.09 $81,306.00
Year 10 $2,522.72 $3,206.32 $78,783.28
Year 11 $2,625.49 $3,103.55 $76,157.79
Year 12 $2,732.47 $2,996.57 $73,425.32
Year 13 $2,843.77 $2,885.27 $70,581.55
Year 14 $2,959.66 $2,769.38 $67,621.89
Year 15 $3,080.22 $2,648.82 $64,541.67
Year 16 $3,205.73 $2,523.31 $61,335.94
Year 17 $3,336.33 $2,392.71 $57,999.61
Year 18 $3,472.25 $2,256.79 $54,527.36
Year 19 $3,613.72 $2,115.32 $50,913.64
Year 20 $3,760.94 $1,968.10 $47,152.70
Year 21 $3,914.16 $1,814.88 $43,238.54
Year 22 $4,073.64 $1,655.40 $39,164.90
Year 23 $4,239.63 $1,489.41 $34,925.27
Year 24 $4,412.33 $1,316.71 $30,512.94
Year 25 $4,592.09 $1,136.95 $25,920.85
Year 26 $4,779.21 $949.83 $21,141.64
Year 27 $4,973.91 $755.13 $16,167.73
Year 28 $5,176.55 $552.49 $10,991.18
Year 29 $5,387.45 $341.59 $5,603.73
Year 30 $5,603.73 $122.11 $0.00
(source: http://web5.vlending.com/loancenter-calculators-amort.aspx. Any mortgage calculator should produce a similar schedule, however.)
A few things to note:
The interest due in the last 6 years is less than the interest due in the first year alone. Banks are getting a disproportionate amount of the expected interest up front.
Banks can make multiple loans; the money collected from existing borrowers can be aggregated to make new loans before the old ones are paid off, and those new loans start, of course, at the interest-heavy end of the repayment schedule. Suppose the bank lends out $1,000,000 to 10 borrowers. In the first two years, they will collect a total of $114588.90 from the 10 borrowers in principal and interest. That's enough to make an additional loan to an 11th borrower while keeping $14,588.90 as "profit". The new borrower is making payments at the year-one rate.
A bank may lose a little interest on a single loan that gets repaid early, but that is generally made up by the fact that a new loan can be issued that much sooner as a result.