This psalm is a kind of confession. David was no longer a refugee, he was now the king in Jerusalem. When you read the story in 2 Samuel 5:1–25 you see that he became proud and haughty. This can be seen from the fact that he took more (pagan?) concubines and wives from Jerusalem (2 Samuel 5:13; see Deuteronomy 17:17) to show what a great king he was. But during the time that he proudly thought not to be moved (Psalm 30:6) he became very ill. And he turned to the Lord. That is Psalm 30:1–12. It was written as a dedication to his palace: David wants to praise the Lord in his new house and not be proud anymore.
1 I will extol you, O LORD, for you have drawn me up and have not let my foes rejoice over me.