The absolute answers are only those that can be arrived at by a direct reference to the text. The only explicit reason given is in 1 kings 2:4, namely that Joab had killed two of David's captains when he sided with Adonijah against his Father David. When Solomon had him killed, the reason given is that he had shed innocent blood in the killing of the two captains.
Beyond this we enter into the realm of deduction and therefore it is much more subjective. The relationship David had with Joab is a complex one. Following the events in which David used Joab to kill Uriah the Hittite there would have been a very strained relationship between the two men. Joab is the one person who could have exposed the treachery of killing Uriah. Keep in mind that when Nathan exposed David in 2 Samuel 12 that the killing of Uriah was not mentioned, only the stealing of his wife Bathesheba. From that day forward, Joab could have exposed David's treachery. Of course that required that Joab also have someone who could protect him for his involvement in the treachery. This is where Adonijah enters into the picture in the events just prior to David's death.
As to why David did not have him killed, at this stage his power to had been so reduced that it was much like it had been in the days of Saul. Absalom and Adonijah had rebelled against their own father and those had taken their toll on David. David had told his son Solomon to "do therefore according to thy wisdom," (1 Kings 2:5) recognizing that there were other realities involved in the killing of Joab. One of the results of killing Joab is that this further strengthened Solomon's position against potential rivals to the throne because the captain who had sided with Adonijah had been killed.
One final point -- In 2 Samuel 12:10-11 Nathan the prophet told David that strife and killing would never depart from David and that it would come from his own house. This was fulfilled in the events of Absalom and Adonijah. God was forgiving of David (2 Sam 12:13) yet there would be permanent consequences for David's sin. The child would die and there would be endless strife. We sometimes think that forgiveness means that all the earthly consequences of sin have been removed. Forgiveness means that the damage done to our relationship with God has been restored, regardless of any temporary effect it might have on us on this earth.