The Spanish giants added the 23-year-old Brazil international, who plays mainly at right back, has a six-year contract until June 30, 2021 at the Bernabeu.
The fee for Danilo is 31.5 million euros, Porto said in a statement to the Portuguese stock exchange.
Danilo started his career at Brazilian club America before joining Santos and then moving to Porto in January 2012 where he has won two Portuguese league titles.
Danilo, who won a silver medal at the 2012 London Olympics, has become a regular for Brazil since Dunga took over as manager after last year's World Cup.
Danilo has also helped Julen Lopetegui's Porto side reach the Champions League quarter-finals where they will play Bayern Munich next month.
He will compete for a starting place in Madrid with Daniel Carvajal and former Liverpool defender Alvaro Arbeloa.

Latest News from Sports News Desk