You should use COUNTIF instead of COUNTA:
=COUNTIF($D$2:D2,D2)
COUNTA()
just counts non-empty cells, COUNTIF()
is a conditional count.
In this formula you're telling COUNTIF to look in range D2 through D2, to look for argument D2; once dragged own, it'll look in range D2 through D3, for argument D3, and so on.
Or using Black cat's comment:
=IF(D3<>D2,1,A2+1)