It is permissible to keep a dog as a guard dog, so long as you avoid letting it inside the house and are careful to avoid letting it make vessels and clothes naajis (impure), because the Prophet (peace and blessings of Allah be upon him) said: “Whoever keeps a dog, his reward for good deeds will decrease by one qeeraat every day, except dogs used for farming or herding livestock.” Narrated by al-Bukhaari, 2322.
The version narrated by Muslim (1574) says: “Whoever keeps a dog, except a dog for hunting or herding livestock, his reward will be decreased by two qeeraats every day.”
Dogs used for farming or herding livestock are those that are used to guard them.
This hadeeth indicates that it is permissible to keep a dog to guard one’s property.
Al-‘Iraaqi said in Tarh al-Tathreeb, 6/28: Our companions and others said: it is permissible to keep a dog for these three purposes, namely hunting and protecting one’s livestock and farmland. They differed concerning keeping a dog for the fourth purpose, which is to guard houses or roads etc. Some of our companions said that it is not permissible because of this hadeeth and others, which clearly state that it is haraam except for one of these three things. But most of them said, which is the more correct view, that it is permissible by way of analogy, based on the reason that may be understood from this hadeeth, which is necessity.”
With regard to preventing the dog from entering the house, that is because of the words of the Prophet (peace and blessings of Allah be upon him): “The angels do not enter a house in which there is a dog or an image.”
Narrated by al-Bukhaari, 3322; Muslim, 2106.
And Allah knows best.
(Source - Islam Q&A)