Alongside a picture of him waving goodbye, the 35-year-old Spain international wrote on Twitter: "Lived it. Loved it. Farewell beautiful game."
He won club honours with Liverpool, Real Madrid and Bayern and the World Cup and two European Championships.
Alonso told Bayern's TV channel: "It wasn't an easy decision to make, but I believe it's the right time.
He added: "I always thought it would be better to quit sooner rather than later. I still feel good, but I believe this is the right moment."
Alonso joined Liverpool from Real Sociedad in 2004 and was part of a famous Champions League victory in Istanbul in his first season as the Reds came back from 3-0 down at half-time to beat AC Milan on penalties. He also claimed an FA Cup, a Uefa Super Cup and a Community Shield during his time at Anfield.
He moved to Real Madrid in 2009 and won a second Champions League as well as the Spanish title before a switch to Germany in 2014, where he has helped Bayern win two Bundesliga titles and reach the quarter-finals of this year's Champions League - courtesy of a 10-2 aggregate win over Arsenal on Tuesday.
Alonso played 114 times for Spain and scored 16 goals as the national side won the 2008 and 2012 European Championships, either side of their maiden World Cup triumph in South Africa in 2010. His final appearance for his country came at the 2014 World Cup in Brazil.
Media playback is not supported on this device
Bayern Munich midfielder Xabi Alonso has confirmed he will retire when his contract expires in the summer.