You should put a comma before but only when but is connecting two independent clauses.
I would go to a movie, but it is raining. In this sentence, two sentences are I would go to a movie and It is raining. The two sentences are having their own meanings. You are connecting two independent statements by using a but. In such a case, you require a comma.
I would go to a movie but for the rain. In the sentence, one clause is an independent clause and the other is a dependent clause. The sentence 'for the rain' is not a complete sentence. This is dependent on the sentence what was written before. " I would go to a movie". In such cases, we need not put a comma.
This is what I learned in English grammar. However, the usage of Comma is very confusing and we will many times miss using this punctuation marking correctly.