The 27-year-old passed a medical with Real while he was on international duty with Brazil.
He said: “Everything I’ve always done for Milan has been by mutual agreement, from the moment I arrived until my departure today – I’m leaving by the front door.
“I’ve won everything that I wanted as a player and this is a new motivation for me.
“I’m sure Real Madrid will build a competitive team which can start winning titles again.”
A statement from Real said: “Kaka has successfully passed all the medical tests. He has signed a six-year contract.”
An AC Milan statement said: “We thank the great champion for his contribution to the many victories achieved in the past six years.
“It will be very difficult to fill the void that will be left by Kaka, a shining example of commitment and professionalism.
“We offer him the most cordial and affectionate wishes for the continuation of his sporting career.”