Here's the rule:
* Use a comma before "but" when it connects two independent clauses.
An independent clause is a group of words that can stand alone as a complete sentence.
Example:
* I love to eat pizza, but I'm trying to eat healthier.
In this example, "I love to eat pizza" and "I'm trying to eat healthier" are both complete sentences. The comma before "but" separates them.
No comma is needed when "but" connects a dependent clause to an independent clause:
* I want to go to the park, but it's raining.
"It's raining" is an independent clause, but "I want to go to the park" is a dependent clause because it can't stand alone as a sentence.
If you're unsure whether to use a comma, try reading the sentence aloud. If you naturally pause before "but", you should probably include a comma.